简体   繁体   中英

How to map a table to an enumerable property using entity framework? (Database first)

Suppose I had these two classes:

public class MyClass {
    public int Id { get; set; }
    public IEnumerable<MyData> MyDataCollection { get; set; }
}

public class MyData {
    public int DataId { get; set; }
    public string Data { get; set; }
    public int Id { get; set; }
}

and I had two tables in my database:

MyClasses:
Id
1
2


MyDatas:
DataId     Id       Data
1       -  1    -  "Hello"
2       -  1    -  "World"
3       -  2    -  "Hello World"

How do I use entity framework to link them up, so that I can do:

using (var db = new DataContext()) {
     var data = db.MyClass.Where(c => c.ID == 1).MyDataCollection;
     foreach (var item in data) Console.WriteLine(item.Data);
}

I have the other data but so far I've just written [NotMapped] above the MyDataCollection property, but obviously I want to get rid of that and have it mapped. How do I (correctly) map it?

You can do it by expanding your class with appropriate navigation properties to establish the joins between them by following EF standards

public class MyClass {
    public MyClass()
    {
       MyDataCollection = new List<MyData>();
    }
    public int Id { get; set; }
    public virtual ICollection<MyData> MyDataCollection { get; set; }
}

public class MyData {
    public int DataId { get; set; }
    public string Data { get; set; }
    public int Id { get; set; }
    public virtual MyClass MyClass { get; set; }
}

Make sure these 2 entities are declared in the dbcontext as below

public class MyContext: DbContext 
{
    public MyContext(): base()
    {

    }

    public DbSet<MyClass> MyClasses { get; set; }
    public DbSet<MyData> MyDatas { get; set; }            
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM