如何在 EF Codefirst 中创建可为 null 的属性?
我的“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; }
}
有没有办法让我的 LoanedTo 可以为空?我的意思是书并不总是被借出,对吧!我尝试过
public virtual Loaner? LoanedTo { get; set; }
但我得到: 类型“RebtelTests.Models.Loaner”必须是不可为 null 的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”,
所以我一定在某个地方想错了,但我可以”搞不懂。对你们来说可能很容易挤压。
I have two POCOs in my "Bookshelf" test application:
/// <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; }
}
Is there a way that my LoanedTo could be nullable? I mean a book isn't always loaned, right! I tried
public virtual Loaner? LoanedTo { get; set; }
But I get:
The type 'RebtelTests.Models.Loaner' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
So I must be thinking wrong somewhere, but I can't figure it out. Probably easy squeeze for you guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要做任何特别的事情。类始终可为空。
我刚刚尝试过这个(使用 MVC3):
在我的 Models 目录中:
在我的 HomeController 中:
Web.Config 中的连接字符串:
当我运行应用程序时,视图显示“OK”。这意味着没有抛出异常。当我查看 App_Data 文件夹时,已创建一个 BookContext.sdf 文件。该数据库包含图书和借书表。贷款人的桌子是空的。书籍的一个包含一条记录:
You don't need to do anything special. Classes are always nullable.
I just tried this (with MVC3):
In my Models directory:
In my HomeController:
The connectionstring in Web.Config:
When I run the application, the view displays "OK". This means that no exception was thrown. When I look in my App_Data folder, a BookContext.sdf file has been created. That database contains a table for the Books and the Loaners. The table for the Loaners is empty. The one for the Books contains one record:
如果您谈论的是 int、bool 或 float 等简单属性,请使用 int?、bool? 或 float?
喜欢
If you are talking about a simple property like int, bool, or float use int?, bool?, or float?
like
难道你不能使用这样的东西
然后应该使 LoanedTo 成为可为空的属性
Couldn't you just use something like this
That then should make LoanedTo a nullable property