我一直在努力学习EF codefirst。首先是它不会强制执行唯一的...所以...我试图通过暴露一个只读IEnumerble属性来解决问题,这个属性迫使我使用AddProp方法,如果我想添加任何东西到集...
当我尝试这样做时(这只是下面的“扔掉”示例)我得到了错误。
错误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;
}
}
答案 0 :(得分:3)
正如您在MSDN中看到的那样,EntityTypeConfiguration.HasMany
需要ICollection<TTargetEntity>
。所以你必须在
Props
public virtual ICollection<Prop> Props
答案 1 :(得分:2)
尝试使用ICollection而不是IEnumerable作为Props属性。这应该会使错误消失。
以下是一些帖子,可以帮助您解释为什么要使用IList或ICollection而不是IEnumerable。
ICollection Vs List in Entity Framework
Why does the entity framework need an ICollection for lazy loading?
我还建议为Props的私有属性使用HashSet而不是List
答案 2 :(得分:0)
泛型函数有类型参数,它们试图“猜测”/“推断”类型参数,但有时它会混淆,你必须明确指定它们。我不知道在这种情况下它无法推断的原因,但在你的鞋子里我会尝试类似的东西,因为在这种情况下我想它想知道目标集合的类型。
.HasMany<Prop>(p => p.Props)