【问题标题】:EF CTP 5 create and persist object graph troubleEF CTP 5 创建和持久化对象图问题
【发布时间】:2012-02-26 03:59:09
【问题描述】:

代码:

Something smt = new Something(){
Prop = 123,
Prop2 = "asdad"
}

foreach(var related in relatedsomething)
{
    smt.Related.Add(new Related(){
    relatedprop = 123,
    };
}

运行时给我一个关于空引用的错误。 相关的是虚拟Icollection。 实体中没有定义外键字段。

相反,如果我这样做了

foreach(var related in relatedsomething)
{
db.Related.Add(new Related(){
    relatedprop = 123,
    Something = smt
    };
}

它有效。
虽然,我希望它像第一个 sn-p 一样工作。
难道我做错了什么? '因为在交付的 EF4 中它可以双向工作。

模型类(相关部分):

public class Printer
{
    public int Id { get; set; }
    public string  Name { get; set; }
    public virtual ICollection<Replica> Replicas { get; set; }


}
public class Replica
{
    public int Id { get; set; }
    public virtual Printer Printer { get; set; }


}


public class PrintersContext: DbContext
{
    public DbSet<Printer> Printers { get; set; }
    public DbSet<Replica> Replicas { get; set; }

}

【问题讨论】:

  • 请发布您的对象模型,包括 SomethingRelated 类。谢谢。

标签: entity-framework ef4-code-only


【解决方案1】:

我想我可能遇到了同样的问题。 I posted on MSDN,但没有得到回应。

这可能是 EF 中的一个错误,您必须忍受并解决它。

【讨论】:

    【解决方案2】:

    首先使用代码,您必须在构造函数中启动您的集合。

     class printer
     {
       public virtual ICollection<replica> replicas {get;set;}
        public printer{
          replicas = new HashSet<replica>();
        }
     }
    

    这一切都会再次神奇地工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      相关资源
      最近更新 更多