sql server 2005 database table has column 'createdon' default value set getdate(). trying add record using entity framework. 'createdon' column not getting updated.
did miss property in entity framework, please suggest.
this 1 of few issues problematic entity framework. have class looks this:
public class myentity { // id pk on table auto-increment public int id { get; set; } // createdon datetime, default value public datetime createdon { get; set; } }
now, want insert new element:
using(var context = new yourcontext()) { context.myentities.add(new myentity()) }
entity framework knows how handle auto-increment primary key because of definition in edmx. not try insert value id
property. however, far entity framework concerned, createdon
has value: default datetime
. because entity framework cannot "well, has value should ignore it", actively insert record createdon
property value, bypassing default value on column definition on table.
there no easy way this. can either actively set createdon
property datetime.now
when insert item. or can create interface , extension method pair:
public interface icreatedon { public datetime createdon { get; set; } } public partial class myentity : icreatedon { } public static tentity asnew<tentity>(this tentity entity) tentity : icreatedon { if(entity != null) entity.createdon = datetime.now; return entity; } using(var context = new yourcontext()) { context.myentities.add(new myentity().asnew()) }
edit: expand on point, reason why unresolvable issue because of meaning behind autoincrement
field , field default
value constraint. auto-increment field should, definition, handle server, using seed , jazz. cannot specify value auto-increment field on insert unless have used set identity insert on
. default value, however, hint "if don't specify value, use this". because value types in .net cannot null, there value , entity framework cannot infer default value field, @ time, means want defaulted on sql server.
Comments
Post a Comment