更容易链接实体框架关系?

时间:2013-06-28 20:20:30

标签: c# entity-framework asp.net-mvc-4 entity-relationship

为了规范化,我已经分离了几个模型,它们都应该有一对一的关系。由于在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; }
}

创建新用户时我:

  • 首先创建一个船长
  • 的SaveChanges()
  • 然后创建一个舰队并将船长分配给舰队
  • 的SaveChanges()
  • 然后创建资源并将Fleet分配给资源
  • 的SaveChanges()
  • 然后将舰队分配给船长,将资源分配给舰队。

像这样:

 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已保存到数据库。

0 个答案:

没有答案