你不需要做任何特别的事情。类总是可以为空的。
我刚试过这个(使用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