2017-03-08 84 views
0

我有一个非常简单的对象结构...一个父对象与一些孩子......但它也有一个对这些孩子的参考。实体框架 - 家长有孩子和一个孩子的参考

public class History 
{ 
    [Key] 
    public int Id { get; set; } 

    public virtual HistoryEvent ActiveEvent { get; set; } 

    public virtual List<HistoryEvent> Events { get; set; } 
} 

public class HistoryEvent 
{ 
    [Key] 
    public int Id { get; set; } 

    public string Name { get; set; } 
} 

    static void Main(string[] args) 
    { 
     using (var context = new EfTest()) 
     { 
      var history = new History 
      { 
       Events = new List<HistoryEvent> 
       { 
        new HistoryEvent { Name = "a" }, 
        new HistoryEvent { Name = "b" }, 
        new HistoryEvent { Name = "c" } 
       } 
      }; 

      history.ActiveEvent = history.Events.First(); 

      context.History.Add(history); 

      context.SaveChanges(); 
     } 
    } 

的数据库中创建,并期待我怎么会想到...

Tables

但它不会救...的内部异常给这个...

Exception

请帮忙!

回答

0

这是不能够节省与循环引用一个复杂的对象来说,这会导致EF是混淆哪个对象先保存(指正如果错)

解决这种混乱在另一个之前刚刚插入一个

尝试这样做

 var history = new History 
     { 
      Events = new List<HistoryEvent> 
      { 
       new HistoryEvent { Name = "a" }, 
       new HistoryEvent { Name = "b" }, 
       new HistoryEvent { Name = "c" } 
      } 
     }; 

     //history.ActiveEvent = history.Events.First(); 

     context.History.Add(history); 
     context.SaveChanges();//now every object has an Id 

     history.ActiveEvent = history.Events.First(); 
     context.SaveChanges(); 

,如果你需要改变你的模式,包括手动外键上面的工作`吨(这可能会帮助你进行更多的控制)

public class History 
{ 
[Key] 
public int Id { get; set; } 
public int? ActiveEventId { get; set; } 
[ForeignKey("ActiveEventId")] 
public virtual HistoryEvent ActiveEvent { get; set; } 

public virtual List<HistoryEvent> Events { get; set; } 
} 

和同为HistoryEvent类

public class HistoryEvent 
{ 
    [Key] 
    public int Id { get; set; } 

    public string Name { get; set; } 
    public int? HistoryId {get; set; } 
    [ForeignKey("HistoryId ")] 
    public virtual History history { get; set; } 
} 

然后

  1. 插入历史与空历史事件

  2. 追加手动history.Id历史事件,如

    var Events = new List<HistoryEvent> { 
          new HistoryEvent { Name = "a" ,HistoryId = history.Id}, 
          new HistoryEvent { Name = "b" ,HistoryId = history.Id}, 
          new HistoryEvent { Name = "c" ,HistoryId = history.Id} 
          } 
    
  3. 事件保存

  4. 得到有效EVENTID和更新历史记录

希望这有助于