为了规范化,我已经分离了几个模型,它们都应该有一对一的关系。由于在EF中做1比1关系的困难,我做了以下几点:
public class Fleet : SpaceObject
{
public int Id{ get; set; }
public int? ActiveCaptainId { get; set; }
public int? ResourcesId { get; set; }
[ForeignKey("ActiveCaptainId")]
[Display(Name = "Captain in Command")]
public virtual Captain ActiveCaptain { get; set; }
[ForeignKey("ResourcesId")]
public virtual Resources Resources { get; set; }
}
public class Captain
{
public int Id{ get; set; }
public int? FleetId { get; set; }
[ForeignKey("FleetId")]
public virtual Fleet Fleet { get; set; }
}
public class Resources
{
public int Id{ get; set; }
public int? FleetId { get; set; }
[ForeignKey("FleetId")]
public virtual Fleet Fleet { get; set; }
}
创建新用户时我:
像这样:
Captain newCapt = new Captain();
newCapt.Name = model.
newCapt.UserId = db.UserProfiles.FirstOrDefault(p=>p.UserName == model.UserName).UserId;
db.Captains.Add(newCapt);
db.SaveChanges();
//----Make a new Fleet
Fleet newFleet = new Fleet();
newFleet.ActiveCaptain = newCapt;
newFleet.UserId = db.UserProfiles.FirstOrDefault(p=>p.UserName == model.UserName).UserId;
db.Fleets.Add(newFleet);
db.SaveChanges(); //commit the changes to the database
Resources resources = new Resources();
resources.Fleet = newFleet;
db.Resources.Add(resources);
db.SaveChanges();
newFleet.Resources = resources;
newCapt.Fleet = newFleet;
db.Entry(newFleet).State = System.Data.EntityState.Modified;
db.Entry(newCapt).State = System.Data.EntityState.Modified;
db.SaveChanges();
我觉得必须有一种更简单的方法来做到这一点。有没有办法让它创建一个新的Fleet创建一个新的资源条目和Ships条目等?我可以看到这是不可能的唯一原因是因为我无法将Fleet中的主键链接到Resources / Captains / Ships / etc,直到Fleet已保存到数据库。