如何在EF Codefirst中创建一个可以为空的属性?

Nic*_*ist 1 entity-framework-4 ef-code-first

我的"Bookshelf"测试应用程序中有两个POCO:

/// <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; }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让我的LoanedTo可以为空?我的意思是一本书并不总是借给你,对吧!我试过了

public virtual Loaner? LoanedTo { get; set; }
Run Code Online (Sandbox Code Playgroud)

但我得到:类型'RebtelTests.Models.Loaner'必须是一个不可为空的值类型,以便在泛型类型或方法'System.Nullable'中将其用作参数'T'

所以我一定在某个地方想错了,但我无法弄清楚.可能很容易挤压你们.

Kri*_*aes 6

你不需要做任何特别的事情.类总是可以为空的.

我刚试过这个(用MVC3):

在我的Models目录中:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的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();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Web.Config中的连接字符串:

<add name="BookContext" connectionString="Data Source=|DataDirectory|BookContext.sdf" providerName="System.Data.SqlServerCe.4.0" />
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,视图显示"OK".这意味着没有抛出任何异常.当我查看App_Data文件夹时,已创建BookContext.sdf文件.该数据库包含Books和Loaners的表.Loaners的表是空的.书籍的一个包含一个记录:

ID: 1; Title: "New Title"; Author: "New Author"; ISBN: "New ISBN"; LoanerID: null
Run Code Online (Sandbox Code Playgroud)