为了规范化,我已经分离了几个模型,它们都应该具有一对一的关系。由于在 EF 中很难建立一对一的关系,我做了以下事情:
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; }
}
创建新用户时,我:
- 首先创建一个船长
- 保存更改()
- 然后创建一个舰队并将船长分配给舰队
- 保存更改()
- 然后创建一个 Resources 并将 Fleet 分配给 Resources
- 保存更改()
- 然后将舰队分配给船长,将资源分配给舰队。
像这样:
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();
我觉得必须有一种更简单的方法来做到这一点。有没有办法做到这一点,一旦创建了一个新的舰队,它就会创建一个新的 Resources 条目和 Ships 条目等?我可以看到这是不可能的唯一原因是因为我无法将 Fleet 的主键链接到 Resources/Captains/Ships/etc,直到 Fleet 被保存到数据库中。