实体框架HasForeignKey无法正常工作

时间:2019-02-21 13:50:23

标签: c# entity-framework ef-fluent-api

我在EF 6.2中遇到了HasForeignKey的奇怪行为。

集体寄售具有两个属性Customer和Sender:

function askForProductsIntentHandler(conv, {products}) {}

CustomerId是客户的外键。实体配置如下:

public class Consignment
{
    public Consignment()
    {
        Sender = new Sender();
        Customer = new Customer();
    }

    public string OrderNo { get; set; }

    public Customer Customer { get; set; }
    public Sender Sender { get; set; }

    public int CustomerId { get; set; }
}

客户和发件人的配置几乎相同,除了客户用HasForeignKey属性配置的和发件人使用Map属性的配置。

所以,当我从数据库获取寄售时,就像在查询中一样

    public class ConsignmentEntityConfiguration : EntityTypeConfiguration<Consignment>
{
    public ConsignmentEntityConfiguration()
    {
        HasKey(s => s.OrderNo);

        HasRequired(x => x.Customer)
            .WithMany()
            .HasForeignKey(x => x.CustomerId);

        HasRequired(x => x.Sender)
            .WithMany()
            .Map(x => x.MapKey("SenderId"));
    }
}

public class SenderEntityConfiguration : EntityTypeConfiguration<Sender>
{
    public SenderEntityConfiguration()
    {
        HasKey(x => x.Number);
    }
}

public class CustomerEntityConfiguration : EntityTypeConfiguration<Customer>
{
    public CustomerEntityConfiguration()
    {
        HasKey(x => x.Id);
    }
}

我收到发件人为正确的发件人,但客户为空(所有属性为null或为空)。渴望,延迟和显式加载会产生相同的结果。

SQL Server正常获取和投影Customer,但是EF返回空的Customer(例如在new Customer()之后)

因此,当我从模型中删除CustomerId属性,并使用.Map配置Customer时,一切工作正常。

var consignment = context.Set<Consignment>().Include(x => x.Customer).Include(x => x.Sender).FirstOrDefault();

当我在新的测试项目中(使用简单的类)重新创建相同的模型时,HasForeignKey可以正常工作。

我在原始项目中缺少什么?类非常简单,我对所有配置进行了三遍检查,原始项目和测试项目看起来相同,但是工作方式不同...

稍微简化的类:

         HasRequired(x => x.Customer)
            .WithMany()
            .Map(x => x.MapKey("CustomerId"));

1 个答案:

答案 0 :(得分:0)

您可以尝试添加客户

public virtual ICollection<Consignment> Consignments { get; set; }

并更改为

HasRequired(x => x.Customer)
            .WithMany(x=>x.Consignments)
            .HasForeignKey(x => x.CustomerId);