开发者

Duplicate status row when inserting worker

I am using the entity framework. I have workers table:

Worker(workerId, name, statusId)

I have POCO for worker with navigation property:

class Worker {
   public virtual long workerId {get;set;}
   public开发者_如何学C virtual string name {get;set;}
   public virtual long statusId {get;set;}
   public virtual Status status {get;set;}
}

In order to insert worker, I fill the name, the status id and even the status (the navigation property) with the relevant values. But instead of inserting only the worker, it insert also the status and creates a new row for the same status (even though I fill the statusId and the id inside the status object).

Why does it inserts the record?..


In order to insert, set only statusId and leave status as null.
This will make the insertion without duplicate associations.
If you fill the status object, the framework entity considers it as a new object (or row).


If the status is existing, you should set the statusid with that id. Or you'll have to fetch that status object and assign it to the object property.

In previous EF version, you have to fetch the status object or set entitykey value to status id.


You can attach the Status to the context if you don't want a new one to be created:

var myStatus = new Status { statusId = 123, ... };
var myWorker = new Worker { status = myStatus, ... };

context.Stati.Attach(myStatus);
context.Workers.Add(myWorker)

context.SaveChanges();

If Worker.statusId is an exposed foreign key column, it should also be possible simply to assign it to the new Worker:

var myWorker = new Worker { statusId = 123, status = null, ... };

context.Workers.Add(myWorker)

context.SaveChanges();

It is important here that the navigation property status is null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜