I have two POCOs in my \"Bookshelf\" test application:
///
/// Represents a book
///
public class Book
{
public int ID { get
Couldn't you just use something like this
public virtual Nullable<Loaner> LoanedTo { get; set; }
That then should make LoanedTo a nullable property
You don't need to do anything special. Classes are always nullable.
I just tried this (with MVC3):
In my Models directory:
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; }
}
}
In my 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();
}
}
}
The connectionstring in Web.Config:
<add name="BookContext" connectionString="Data Source=|DataDirectory|BookContext.sdf" providerName="System.Data.SqlServerCe.4.0" />
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:
ID: 1; Title: "New Title"; Author: "New Author"; ISBN: "New ISBN"; LoanerID: null
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; }