2011-01-25 53 views
1

我在我的“书架”测试应用二波苏斯:如何在EF Codefirst中创建一个可为空的属性?

/// <summary> 
/// Represents a book 
/// </summary> 
public class Book 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Author { get; set; } 
    public string ISBN { get; set; } 
    public virtual Loaner LoanedTo { get; set; } 
} 

/// <summary> 
/// Represents a Loaner 
/// </summary> 
public class Loaner 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Book> Loans { get; set; } 
} 

有没有办法,我LoanedTo可能为空的?我的意思是一本书并不总是借出,对!我试图

public virtual Loaner? LoanedTo { get; set; } 

,但我得到: 类型“RebtelTests.Models.Loaner”必须是为了在泛型类型或方法“系统使用它作为参数“T”非空值类型。可空'

所以我必须在某个地方想错,但我无法弄清楚。可能很容易挤你们。

回答

6

你不需要做任何特殊。类总是可以空的。

我只是尝试这样做(与MVC3):

在我的车型目录:

namespace MvcApplication2.Models 
{ 
    public class Book 
    { 
     public int ID { get; set; } 
     public string Title { get; set; } 
     public string Author { get; set; } 
     public string ISBN { get; set; } 
     public virtual Loaner LoanedTo { get; set; } 
    } 

    public class Loaner 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public virtual ICollection<Book> Loans { get; set; } 
    } 

    public class BookContext : System.Data.Entity.DbContext 
    { 
     public System.Data.Entity.DbSet<Book> Books { get; set; } 
     public System.Data.Entity.DbSet<Loaner> Loaners { get; set; } 
    } 
} 

在我的HomeController:

namespace MvcApplication2.Controllers 
{ 
    public class HomeController : Controller 
    { 
     // 
     // GET: /Home/ 

     public ActionResult Index() 
     { 
      string message = "OK"; 

      try 
      { 
       var context = new Models.BookContext(); 
       var book = new Models.Book(); 
       book.Title = "New Title"; 
       book.Author = "New Author"; 
       book.ISBN = "New ISBN"; 
       context.Books.Add(book); 
       context.SaveChanges(); 
      } 
      catch (Exception err) 
      { 
       message = err.ToString(); 
      } 

      ViewBag.Message = message; 

      return View(); 
     } 

    } 
} 

ConnectionString中Web.Config中:

<add name="BookContext" connectionString="Data Source=|DataDirectory|BookContext.sdf" providerName="System.Data.SqlServerCe.4.0" /> 

W当我运行应用程序时,视图显示“OK”。这意味着不会抛出异常。当我查看我的App_Data文件夹时,已经创建了一个BookContext.sdf文件。该数据库包含书籍和贷款人的表格。 Loaners表为空。在一个用于丛书包含一个记录:

ID: 1; Title: "New Title"; Author: "New Author"; ISBN: "New ISBN"; LoanerID: null 
+0

哇,我想我应该有测试我的数据库和类移动到下一个步骤。原来你是对的。更糟糕的是我的应用程序是错误的。谢谢 –

-1

你不能只是用这样的

public virtual Nullable<Loaner> LoanedTo { get; set; } 

这则应该LoanedTo可空的属性

+2

贷款人是一个类(引用类型),该语句将不能编译 –

1

如果你谈论的是一个简单的属性如int,BOOL,或浮动使用int?布尔?还是浮动?

public int? ID { get; set; } 
public bool? Exists { get; set; } 
相关问题