开发者

Entity framework code first: why is my collection not created?

开发者 https://www.devze.com 2023-02-19 19:01 出处:网络
I have some class called myDB that inherits from DbContext the class contains the following member : public DbSet&开发者_开发问答lt;Zoo> mAllZoos { get; set; }

I have some class called myDB that inherits from DbContext the class contains the following member :

public DbSet&开发者_开发问答lt;Zoo> mAllZoos { get; set; }

the Zoo class looks like this :

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

there is an "Animal" class which is not relevant at all, but it does contain "ID".

when i ask him to create a Database from my classes he creates a Table named Animal for my animals, and a table Zoo for my zoos..

In the zoo table, there are only "Size" and "Name" fields And in the animal table there are ID and other properties but no reference to the Zoo.

The bottom line is that there is no reference from the animals to the zoos , so i can't save which animal is in which zoo ..

What did i do wrong ? And how do i fix it.

Thanks in advance


I believe you need to declare an Animal DbSet in your context as well

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

Does the animal class have an ID property or at least a property marked with the KeyAttribute? Entity Framework will use that ID (or key) to create the Foreign Key relation between the tables.

By the way, you'll have to mark the Animals property in the Zoo class as virtual if you want Lazy Loading to work:

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

精彩评论

暂无评论...
验证码 换一张
取 消