entity framework 4 - How to make a nullable property in EF Codefirst? -
i have 2 pocos in "bookshelf" test application:
/// <summary> /// represents 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 loaner /// </summary> public class loaner { public int id { get; set; } public string name { get; set; } public virtual icollection<book> loans { get; set; } }
is there way loanedto nullable? mean book isn't loaned, right! tried
public virtual loaner? loanedto { get; set; }
but get: type 'rebteltests.models.loaner' must non-nullable value type in order use parameter 't' in generic type or method 'system.nullable'
so must thinking wrong somewhere, can't figure out. easy squeeze guys.
you don't need special. classes nullable.
i tried (with mvc3):
in 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 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 run application, view displays "ok". means no exception thrown. when in app_data folder, bookcontext.sdf file has been created. database contains table books , loaners. table loaners empty. 1 books contains 1 record:
id: 1; title: "new title"; author: "new author"; isbn: "new isbn"; loanerid: null
Comments
Post a Comment