C# 如何获得;“儿童”;任意对多关系EF6中的直接行
我有这样的多对多关系的EF6模型(我简化了模型以使其更清晰): 我需要直接在我的卡对象中收集布局。我不想通过关系表。我想这样使用它:C# 如何获得;“儿童”;任意对多关系EF6中的直接行,c#,entity-framework-6,C#,Entity Framework 6,我有这样的多对多关系的EF6模型(我简化了模型以使其更清晰): 我需要直接在我的卡对象中收集布局。我不想通过关系表。我想这样使用它: int exampleId = 23; using (MyContext ctx = new MyContext()) { Card c = ctx.Cards.Find(23); foreach (Layout layout in c.Layouts) { DoSomethingWithLayout(la
int exampleId = 23;
using (MyContext ctx = new MyContext())
{
Card c = ctx.Cards.Find(23);
foreach (Layout layout in c.Layouts)
{
DoSomethingWithLayout(layout);
}
}
我试过这样的方法:
public class Card
{
public int CardId { get; set; }
public string CardTitle { get; set; }
public virtual ICollection<CardLayout> CardLayouts { get; set; }
public virtual ICollection<Layout> Layouts { get; set; }
}
公共类卡
{
公共int-CardId{get;set;}
公共字符串CardTitle{get;set;}
公共虚拟ICollection卡片布局{get;set;}
公共虚拟ICollection布局{get;set;}
}
但是Layouts
集合总是空的
我的问题是:如何直接从卡对象访问Layouts集合?我也想保留Card.CardLayouts集合,因为我的CardLayouts表包含字段(如简化示例中的CardLocation)
有人能改进我的问题标题吗?我的英语不够好,写不好。提前谢谢。而我认为@Biscuits的评论是正确的。如果出于任何原因您不想走这条路线,您应该只能够使用getter创建另一个属性
public class Card
{
public int CardId { get; set; }
public string CardTitle { get; set; }
public virtual ICollection<CardLayout> CardLayouts { get; set; }
[NotMapped]
public IEnumerable<Layout> Layouts
{
get
{
return this.CardLayouts.Select(cl => cl.Layout);
}
}
}
公共类卡
{
公共int-CardId{get;set;}
公共字符串CardTitle{get;set;}
公共虚拟ICollection卡片布局{get;set;}
[未映射]
公共可数布局
{
得到
{
返回此.CardLayouts.Select(cl=>cl.Layout);
}
}
}
而我认为@bickets的评论是正确的。如果出于任何原因您不想走这条路线,您应该只能够使用getter创建另一个属性
public class Card
{
public int CardId { get; set; }
public string CardTitle { get; set; }
public virtual ICollection<CardLayout> CardLayouts { get; set; }
[NotMapped]
public IEnumerable<Layout> Layouts
{
get
{
return this.CardLayouts.Select(cl => cl.Layout);
}
}
}
公共类卡
{
公共int-CardId{get;set;}
公共字符串CardTitle{get;set;}
公共虚拟ICollection卡片布局{get;set;}
[未映射]
公共可数布局
{
得到
{
返回此.CardLayouts.Select(cl=>cl.Layout);
}
}
}
听起来您需要引入一个业务层来提供域对象/模型和数据库实体之间的隔离。使用LINQ,您应该能够投影到一个IQueryable
,它以您想要的方式折叠复杂的关系。听起来您需要引入一个业务层来提供域对象/模型和数据库实体之间的隔离。使用LINQ,您应该能够投影到一个IQueryable
,它以您想要的方式折叠复杂的关系。
public class Card
{
public int CardId { get; set; }
public string CardTitle { get; set; }
public virtual ICollection<CardLayout> CardLayouts { get; set; }
[NotMapped]
public IEnumerable<Layout> Layouts
{
get
{
return this.CardLayouts.Select(cl => cl.Layout);
}
}
}