地图弱实体先用code先用、实体、地图、code

由网友(蛋疼就捂着!)分享简介:您好我已经开发了模型,完美的作品对我来说,现在我想用的EntityFramework它映射到数据库中,这里是其中的一部分:Hi I have developed model that works perfectly for me, now I want to map it to database using Enti...

您好我已经开发了模型,完美的作品对我来说,现在我想用的EntityFramework它映射到数据库中,这里是其中的一部分:

Hi I have developed model that works perfectly for me, now I want to map it to database using EntityFramework, here is a part of it:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ProductType Type { get; set; }
}

public class Supplier
{
    public int Id { get; set; }
    public string OIB { get; set; }
    public string Name { get; set; }
}

public class SupplierProduct
{
    public double Price { get; set; }
    public string SupplierMark { get; set; }

    public virtual Product Product { get; set; }
    public virtual Supplier Supplier { get; set; }
}

现在我的问题是我怎么写模型构建实体配置形成我的DbContext,以便其映射在SupplierProduct类ForeignKeys Supllier.ID和Product.Id为DB关系的主键。

Now my question is how do I write entity configuration on ModelBuilder form my DBContext so that it maps on SupplierProduct class ForeignKeys Supllier.ID and Product.Id as Primary key of DB relation.

推荐答案

我用数据标注,但我希望你正在寻找以下内容:

I use data annotations, but I expect you're looking for the following:

产品公司 SupplierProduct ,指定这些ID字段FK的,然后定义有两个ID字段复合主键

define ID properties for Product and Supplier in SupplierProduct, specify these ID fields as FK's, then define compound primary key with the two ID fields

modelBuilder.Entity<SupplierProduct>()
    .HasRequired( sp => sp.Product)
    .WithMany( p => SupplierProducts )
    .HasForeignKey( sp => sp.ProductId );

modelBuilder.Entity<SupplierProduct>()
    .HasRequired( sp => sp.Supplier)
    .WithMany( s => SupplierProducts )
    .HasForeignKey( sp => sp.SupplierId );

modelBuilder.Entity<SupplierProduct>()
    .HasKey(sp=> new { sp.ProductId, sp.SupplierId });