orm - How to set default values for foreign keys in Entity Framework code-first models -
i'm using entity framework 5, code-first.
i have poco looks this:
public class order { public int id { get; set; } public string name { get; set; } public virtual status status { get; set; } public order() { this.status = new status() { id = 1 } } }
this mapped fluently like:
public class ordermap : entitytypeconfiguration<order> { public ordermap() { totable("order"); haskey(x => x.id); property(x => x.id); property(x => x.name).isrequired(); hasrequired(x => x.status) .withmany(x => x.orders) .map(x => x.mapkey("statusid")); } }
in database, order
table has default value of statusid
set 1
.
however, when adding new order
, error:
violation of primary key constraint 'status_pk'. cannot insert duplicate key in object 'dbo.status'. duplicate key value (1)
if remove assignment status
in order
ctor, instead:
cannot insert value null column 'statusid', table 'mydatabase.dbo.order'; column not allow nulls. insert fails
how can set default values foreign key properties?
provide default status order via constructor (otherwise new status inserted, because whole graph in added state):
public class order { public int id { get; set; } public string name { get; set; } public virtual status status { get; set; } public order(status initialtstatus) { status = initialtstatus; } }
and use this:
var status = db.statuses.find(1); var order = new order (status) { name = "lazy" }; db.orders.add(order); db.savechanges();
update: option attaching default status entity context or setting it's state manually:
var order = new order { name = "lazy" }; db.entry(order.status).state = entitystate.unchanged; // avoid inserting db.orders.add(order); db.savechanges();
Comments
Post a Comment