简体   繁体   中英

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. 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.

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.

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.

I believe that you modelling could be improved... Promotion should not extend 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...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM