[英]EF 6 Retrieve parent for child autogenerated foreign key
I'm using the following couple of entities: 我正在使用以下几个实体:
public class Store {
public int Id { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Promotion> Promotions { get; set; }
}
public class Product {
[product properties here...]
}
public class Promotion : Product {
[extra promotion properties here...]
}
By using Code First it generated my database. 通过使用Code First,它生成了我的数据库。 It generated a Products table, with a discriminator (in order to discriminate which type of class it is storing) and then a Store_Id foreign key that is filled when it is a Product and another Store_Id1 that is used when using promotions.
它生成了一个Products表,带有一个鉴别器(为了区分它所存储的类型),然后是一个Store_Id外键,当它是Product时填充,另一个Store_Id1在使用促销时使用。
Now, after a time, I need to access the store from a specific Promotion. 现在,过了一段时间,我需要从特定的促销活动访问商店。 How can it be done?
如何做呢? I tried using Fluent and telling it about the Foreign Keys but I failed.
我尝试使用Fluent并告诉它外键但我失败了。
Can you guys bring me some light on this? 你们能告诉我一些事吗?
Thanks, 谢谢,
Isn't this just a simple many-to-one relationship? 这不仅仅是一个简单的多对一关系吗?
public int StoreID { get; set; }
public virtual Store Store { get; set; }
public int Store1ID { get; set; }
public virtual Store Store1 { get; set; }
modelBuilder.Entity<Store>()
.HasMany(m => m.Products)
.WithRequired(m => m.Store);
modelBuilder.Entity<Store>()
.HasMany(m => m.Promotions)
.WithRequired(m => m.Store1);
Product.Store
and Product.Store1
would then just be navigation properties back to their Stores. Product.Store
和Product.Store1
只是导航属性回到他们的商店。
I believe that you modelling could be improved... Promotion
should not extend Product
. 我相信你的建模可以改进......
Promotion
不应该扩展Product
。 You should decouple them, having a promotion point to a product and a store (if you want store specific promotions)... meaning that Product
and Store
should be a field in the Promotion
entity... Expanding a bit further, imagine what would it look like if you want to have a single promotion involving more than one product (eg: soap and shampoo, running sneaker and socks, etc...) 您应该将它们分离,将促销点放到产品和商店(如果您想要商店特定促销)...意味着
Product
和Store
应该是Promotion
实体中的一个字段...进一步扩展,想象什么会看起来如果您想进行涉及多种产品的单一促销活动(例如:肥皂和洗发水,运动鞋和袜子等......)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.