EF代码优先:同一收集类型一对多 [英] EF code first: one-to-many twice to same collection type

查看:52
本文介绍了EF代码优先:同一收集类型一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简化的:在我的数据库中,我有一种产品在不同的日期以不同的价格出售.换句话说,它具有价格历史记录.我有两个类:具有一对多关系的 Product Price :

Simplified: In my DB I have a product that was sold with different prices on different dates. In other words it has a Price History. I have two classes: Product and Price with a one-to-many relationship:

public class Product
{
    public int ProductId {get; set;}
    public string Name {get; set;}

    public ICollection<Price> Prices {get; set;}
}

public class Price
{
    public int PriceId {get; set;}

    // foreign key to Product:
    public int ProductId {get; set;}
    public Product Product {get; set;}

    public DateTime ActivationDate {get; set;}
    public decimal value {get; set;}
}

public class MyDbContext : DbContext
{
    public DbSet<Price> Prices { get; set; }
    public DbSet<Product> Products { get; set; }
}

到目前为止,Entity Framework知道如何处理.通过使用这两个类,我可以在特定日期获得特定产品的价格.

So far so good, Entity Framework knows how to handle this. With the use of these two classes I am able to get the price of a certain product on a certain date.

但是,如果我的产品有两个价格历史记录:购买价格历史记录和零售价格历史记录?

But what if my product has two price histories: a Purchase Price history and a Retail Price History?

public class Product
{
    public int ProductId {get; set;}
    public string Name {get; set;}

    public ICollection<Price> PurchasePrices {get; set;}
    public ICollection<Price> RetailPrices {get; set;}  
}

因为这两个集合属于同一类型,所以我不想用相同类型的对象填充单独的表(真正的原因:我有很多带有价格集合的类).

Because these two collections are to the same type I don't want separate tables filled with object of the same type (the real reason: I have a lot of classes with price collections).

因此,我必须使用Fluent API进行一些编码.我的直觉说我需要像使用多对多关系那样连接表,可以通过使用ManyToManyNavigationPropertyConfiguration.Map.

So I have to do a bit of coding using Fluent API. My gut feeling says I need joining tables, like in a many-to-many relationship, mayby using the ManyToManyNavigationPropertyConfiguration.Map.

该怎么做?

推荐答案

阅读了有关

After reading a story about one-to-one foreign key associations and using this for a one-to-many association I was able to implement it with the following requirements:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆