EntityFrameworkCore映射关系

时间:2017-11-14 16:05:55

标签: c# entity-framework ef-code-first entity-framework-core

我有以下两个实体:

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
}

这对应于两个DB表:

Company:
  Id uniqueidentifier
  Name varchar

Address:
  Id uniqueidentifier
  Town varchar
  Country varchar
  RelationId uniqueidentifier

RelationId是将链接存储回CompanyId的外键。

无法更改类或表。

我试图弄清楚如何在代码中首先表示这个构造EFCore。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>().ToTable("Companies");
        modelBuilder.Entity<Address>().ToTable("Addresses");

        modelBuilder.Entity<Company>().HasKey(c => c.Id);
        modelBuilder.Entity<Address>().HasKey(c => c.Id);

        ???????????????????????
    }

我在上面的代码中遗漏了什么,以防止创建CompanyId外键并使用&#39; RelationId&#39;代替。

2 个答案:

答案 0 :(得分:2)

在@TanvirArjel的目的下,在地址中创建Guid RelationId和Company公司属性,并使用以下流畅的配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    .....

    modelBuilder.Entity<Company>()
        .HasOne(c => c.Address)
        .WithOne(a => a.Company)
        .HasForeignKey(a => a.RelationId);
}

如果地址可以包含多个公司,请将WithOne更改为WithMany,将公司媒体资源类型更改为ICollection<Company>

答案 1 :(得分:1)

以下是符合您要求的解决方案:

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    //remove virtual keyword as there is no lazy loading in  entityframework core
    public ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }

    [ForeignKey("Company ")]
    public Guid RelationId { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }

    //remove virtual keyword as there is no lazy loading in  entityframework core
    public Company Company {get; set;}
}

使用Fluent API:

public class YourDbContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Address> Addresses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>()
            .HasOne(p => p.Company)
            .WithMany(b => b.Addresses);
    }
}