c# - Entity Framework 代码首先: why is my collection not created?

标签 c# .net ef-code-first

我有一些名为 myDB 的类,它继承自 DbContext 该类包含以下成员:

public DbSet<Zoo> mAllZoos { get; set; }

Zoo 类如下所示:

public class Zoo
{
    public string Name { get; set; }
    public IEnumerable<Animal> Animals { get; set; }
    public int ZooSize { get; set; }
    public int ID { get; set; }
}

有一个“Animal”类,它根本不相关,但它确实包含“ID”。

当我要求他从我的类(class)中创建一个数据库时,他为我的动物创建了一个名为 Animal 的表,并为我的动物园创建了一个名为 Zoo 的表。

在动物园表中,只有“大小”和“名称”字段 在动物表中,有 ID 和其他属性,但没有引用动物园。

最重要的是,没有从动物到动物园的引用,所以我无法保存哪个动物在哪个动物园..

我做错了什么?我该如何解决它。

提前致谢

最佳答案

我相信您还需要在您的上下文中声明一个 Animal DbSet

public DbSet<Animal> Animals { get; set; }

动物类是否有 ID 属性或至少有一个用 KeyAttribute 标记的属性? Entity Framework 将使用该 ID(或键)创建表之间的外键关系。

顺便说一句,如果您希望延迟加载正常工作,则必须将 Zoo 类中的 Animals 属性标记为 virtual :

public virtual IEnumerable<Animal> Animals { get; set; }

关于c# - Entity Framework 代码首先: why is my collection not created?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5444770/

相关文章:

c# - 在 Asp.Net Core 中使用 POST 方法重定向到 URL

c# - Java 与 C# 中的 UTF-16 编码

c# - 为什么 IEnumerable.Count() 的上限为 200?

c# - 如何正确使用 LINQ2SQL DataContext 对象;每次使用重新创建都会让人头疼

c# - 在回传中保留单选/复选框值?

C# WebClient - DownloadString 编码错误

.net - 在 ASP.NET 中使用更少的内存

ef-code-first - 在 Entity Framework 7 中添加/插入包含复杂类型的新条目代码优先

c# - 一个实体可以与多个实体相关联吗?

c# - Include() 不能用作 LEFT JOIN( Entity Framework 6)