c# 4.0 - How to Add Records in a 0:0..N in Entity Framework 5 -
we have ms sql server table structure such:
table org { id int name varchar(50) } table request { id int name varchar(50) orgid int not null } our models this:
public class org { public int id { get; set;} public string name { get; set;} public list<request> requests { get; set;} } public class request { public int id { get; set;} public string name { get; set;} public int orgid { get; set;} } and our configuration such:
public class requestconfiguration : entitytypeconfiguration<request> { public requestconfiguration() { hasrequired(o => o.org) .withmany(o => o.requests) .hasforeignkey(o => o.orgid); } } every time go make new request instance, , assign org it, creates new record in org table - no matter what. on same dbcontext. i've tried various mappings in configuration, result in same behavior. doing wrong?
thanks!
you must tell ef org exists. otherwise ef assume org new , want insert database. can can either loading existing org database or attaching context:
using (var context = new mycontext()) { var newrequest = new request(); var existingorg = new org { id = existingorgid }; context.orgs.attach(existingorg); // or instead of previous 2 lines: // var existingorg = context.orgs.find(existingorgid); newrequest.org = existingorg; context.requests.add(newrequest); context.savechanges(); } this insert new request foreign key of orgid refering existing org.
actually because have foreign key property don't need org instance @ all. can set fk value:
var newrequest = new request(); newrequest.orgid = existingorgid; context.requests.add(newrequest); context.savechanges();
Comments
Post a Comment