如果您知道您的状态类型已经存在,那么您现在还必须使用它的主键。一旦你有一个主键值,你可以使用这种方法:
var newStatus = new Status {
StatusId = status.Id,
UserId = user.Id,
Text = status.text,
CreateDate = DateTime.Now
};
// Just dummy object for existing status type
var existingStatusType = new StatusType {
Id = existingStatusTypeId
};
// Persist need status to database
using (var db = new demoEntities())
{
db.Statuses.AddObject(newStatus);
// First let EF know that the status type already exists
// Attaching prior to making relation is important!
db.StatusTypes.Attach(existingStatusType);
// Now make relation between new and existing entity
newStatus.StatusTypes.Add(existingStatusType);
db.SaveChanges();
}
如果您不想在持久性代码中创建关系,则必须使用一些不同的方法。
var newStatus = new Status {
StatusId = status.Id,
UserId = user.Id,
Text = status.text,
CreateDate = DateTime.Now
};
// Just dummy object for existing status type
var existingStatusType = new StatusType {
Id = existingStatusTypeId
};
newStatus.StatusTypes.Add(existingStatusType);
// Persist need status to database
using (var db = new demoEntities())
{
// This will add both newStatus and existingStatusType as new entities
db.Statuses.AddObject(newStatus);
// You must fix it to make sure that existingStatusType is not inserted
// to database again
status.StatusTypes.ForEach(st =>
db.ObjectStateManager.ChangeObjectState(st, EntityState.Unchanged));
db.SaveChanges();
}