2011-01-25 52 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; } 
相關問題