[英]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. 我还有其他数据,但到目前为止,我只是在
MyDataCollection
属性上方编写了[NotMapped],但显然我想摆脱它并进行映射。 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 您可以通过使用适当的导航属性扩展类以遵循EF标准在它们之间建立连接来做到这一点
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 确保这两个实体在dbcontext中声明如下
public class MyContext: DbContext
{
public MyContext(): base()
{
}
public DbSet<MyClass> MyClasses { get; set; }
public DbSet<MyData> MyDatas { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.