gpt4 book ai didi

c# - Entity Framework - 无法从使用中推断出来

转载 作者:太空狗 更新时间:2023-10-30 01:06:00 25 4
gpt4 key购买 nike

我一直在努力学习 EF codefirst。第一件事是它不会强制执行唯一...所以...我试图通过公开一个只读的 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;
}
}

最佳答案

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

public virtual ICollection<Prop> Props

关于c# - Entity Framework - 无法从使用中推断出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com