我在这里看过类似的问题,但没有看到这个具体情况。
使用EF 6 Code First,我有三个表,A,B和C.关系是A => B = 1:M,B => C = 1:1
此架构的最终结果是A和C之间存在隐式1:M。
我不希望实体框架模型的使用者了解B.理想情况下,他们将拥有从A到C的1:M导航属性(我希望能够通过Web API显示此实体模型和OData为IQueryable)
我怎么能这样做?
如果我将自定义[NotMapped]属性添加到A的C集合,我无法在该属性的getter中填充C,因为该实体不知道它的上下文。
任何人都有任何关于如何实现IQueryable的想法,其中A具有C的导航属性而B被“抽象”不存在?
修改
尝试将以下内容放入代码第一个实体A:
[NotMapped]
public ICollection<C> Cs
{
get { return this.Bs.Select(b => b.C) as ICollection<C>; }
}
但是得到了这个错误: 导航属性“C”不是“A”类型的声明属性。验证它是否未从模型中明确排除,并且它是有效的导航属性。
感谢。
答案 0 :(得分:0)
这是一个例子。
public static class OrderDAL
{
public static Order Get(int key)
{
using (var context = new AppContext())
{
var order = context.Orders.Include(a => a.OrderDetails.Select(b => b.Information)).FirstOrDefault(a => a.Id == key);
// Fills C.
order.OrderDetailAdditionalInformation = order.OrderDetails.Select(b => b.Information).ToArray();
// Hides information about B.
foreach (var information in order.OrderDetailAdditionalInformation)
{ information.OrderDetail = null; }
order.OrderDetails = null;
return order;
}
}
}
public class AppContext : DbContext
{
public DbSet<Order> Orders { get; set; }
}
// A
public class Order
{
public int Id { get; set; }
public DateTime Date { get; set; }
public ICollection<OrderDetail> OrderDetails { get; set; }
[NotMapped]
public ICollection<OrderDetailAdditionalInformation> OrderDetailAdditionalInformation { get; set; }
}
// B, one A many B
public class OrderDetail
{
public int Id { get; set; }
public int Qty { get; set; }
public string Item { get; set; }
public int OrderId { get; set; }
public Order Order { get; set; }
public OrderDetailAdditionalInformation Information { get; set; }
}
// C, one B one C
public class OrderDetailAdditionalInformation
{
[ForeignKey("OrderDetail")]
public int Id { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Long { get; set; }
public OrderDetail OrderDetail { get; set; }
}