[英]How to map a property to database table column explicitly in codefirst Entity framework
[英]How to map a table to an enumerable property using entity framework? (Database first)
假設我有以下兩個類:
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; }
}
我的數據庫中有兩個表:
MyClasses:
Id
1
2
MyDatas:
DataId Id Data
1 - 1 - "Hello"
2 - 1 - "World"
3 - 2 - "Hello World"
我如何使用實體框架將它們鏈接起來,以便可以執行以下操作:
using (var db = new DataContext()) {
var data = db.MyClass.Where(c => c.ID == 1).MyDataCollection;
foreach (var item in data) Console.WriteLine(item.Data);
}
我還有其他數據,但到目前為止,我只是在MyDataCollection
屬性上方編寫了[NotMapped],但顯然我想擺脫它並進行映射。 我如何(正確)映射它?
您可以通過使用適當的導航屬性擴展類以遵循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; }
}
確保這兩個實體在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.