4

我一直在尝试先学习 EF 代码。首先要做的事情之一是它不会强制执行唯一性......所以......我试图通过公开一个只读的 IEnumerble 属性来解决这个问题,如果我想向收藏...

当我尝试这样做时(这只是下面的“扔掉”示例)我得到了错误。

错误 1 ​​无法从用法中推断方法“System.Data.Entity.ModelConfiguration.EntityTypeConfiguration.HasMany(System.Linq.Expressions.Expression>>)”的类型参数。尝试明确指定类型参数。C:\Users\User\Documents\Visual Studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 39 9 ConsoleApplication3

有什么理由吗?

class Program
{
  static void Main(string[] args)
  {
    using (DC _db = new DC())
    {
      PrimeA p = new PrimeA { Name = "BlahGEEEER" };
      p.AddProp(new Prop { comment = "Blah HI!" });
      p.AddProp(new Prop { comment = "Blah HI!" });


      Console.ReadLine();
      _db.PrimeAs.Add(p);
      _db.SaveChanges();
    }
  }
}

public class DC : DbContext
{
  public DbSet<PrimeA> PrimeAs { get; set; }
  public DbSet<PrimeB> PrimeBs { get; set; }
  public DbSet<Prop> Props { get; set; }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<PrimeA>()
      .HasMany(p => p.Props)  // <---- FAILS HERE
      .WithMany();

    base.OnModelCreating(modelBuilder);
  }
}

public class PrimeA
{

  private List<Prop> m_Props = new List<Prop>();

  public int PrimeAID { get; set; }
  public string Name { get; set; }
  public virtual IEnumerable<Prop> Props
  {
    get 
    {
      return m_Props;
    }

  }

  public bool AddProp(Prop prop)
  {
    bool ret = false;
    var existingResult =
      from p in m_Props
      where p.comment.ToLower() == prop.comment.ToLower()
      select p;
    if (existingResult.Count() == 0)
    {
      m_Props.Add(prop);
      ret = true;
    }
    return ret;
  }
}
4

3 回答 3

3

正如您在MSDN中看到的那样,EntityTypeConfiguration.HasMany需要一个ICollection<TTargetEntity>. 所以你必须Props改变

public virtual ICollection<Prop> Props
于 2013-05-30T23:07:41.137 回答
2

尝试对 Props 属性使用 ICollection 而不是 IEnumerable。那应该使错误消失。

这里有几篇文章有助于解释为什么要使用 IList 或 ICollection 而不是 IEnumerable。

实体框架中的 ICollection 与列表

为什么实体框架需要一个 ICollection 来进行延迟加载?

我还建议对 Props 的私有财产使用 HashSet 而不是 List

于 2013-05-30T23:10:06.707 回答
0

泛型函数具有类型参数,它们试图“猜测”/“推断”类型参数,但有时它会混淆,您必须明确指定它们。我不知道在这种情况下它无法推断的原因,但在你的鞋子里我会尝试类似的东西,因为在这种情况下我认为它想知道目标集合的类型。

.HasMany<Prop>(p => p.Props) 
于 2013-05-30T23:02:02.260 回答