1

我的“书架”测试应用程序中有两个 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; }
}

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

public virtual Loaner? LoanedTo { get; set; }

但我得到:“RebtelTests.Models.Loaner”类型必须是不可为空的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”

所以我一定在某个地方想错了,但我想不通。对你们来说可能很容易挤压。

4

3 回答 3

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

    }
}

Web.Config 中的连接字符串:

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

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

ID: 1; Title: "New Title"; Author: "New Author"; ISBN: "New ISBN"; LoanerID: null
于 2011-01-26T11:08:24.110 回答
1

If you are talking about a simple property like int, bool, or float use int?, bool?, or float?

like

 public int? ID { get; set; }
 public bool? Exists { get; set; }
于 2012-11-22T17:21:51.920 回答
-1

你不能就用这样的东西吗

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

那应该使 LoanedTo 成为可为空的属性

于 2011-01-26T07:05:32.800 回答