EF懒加载和流畅的API创建表的其他领域(EF lazy loading & fluent API

2019-10-18 20:48发布

这里是我的代码-首先, Attachment类:

    public class Attachment{
    (...)
          public int UserId { get; set; }
          public virtual User Author { get; set; }

          public int? BasicMedicalDataId { get; set; }
          public virtual BasicMedicalData MedicalData { get; set; }
    }

这里是BasicMedicalData类:

    public class BasicMedicalData{
    (..)
          public virtual ICollection<Attachment> Attachments { get; set; }
    }

正如你所看到的, Attachment可以任选一种连接BasicMedicalData对象。 BasicMedicalData可以有很多的Attachments对象。

有了这些行

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        (..)
        modelBuilder.Entity<Attachment>()
            .HasOptional(u => u.MedicalData)
            .WithMany()
            .HasForeignKey(u => u.BasicMedicalDataId);


        modelBuilder.Entity<Attachment>()
            .HasRequired(a => a.Author)
            .WithMany()
            .HasForeignKey(a => a.UserId);

    }

它创建怪迁移:

    public override void Up()
    {
        CreateTable(
            "dbo.Attachments",
            c => new
                {
                    AttachmentId = c.Int(nullable: false, identity: true),
                    name = c.String(),
                    UserId = c.Int(nullable: false),
                    AddDate = c.DateTime(nullable: false),
                    BasicMedicalDataId = c.Int(),
                    del = c.Boolean(nullable: false),
                    BasicMedicalData_BasicMedicalDataId = c.Int(),
                })
            .PrimaryKey(t => t.AttachmentId)
            .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true)
            .ForeignKey("dbo.PC_BasicMedicalData", t => t.BasicMedicalData_BasicMedicalDataId)
            .ForeignKey("dbo.PC_BasicMedicalData", t => t.BasicMedicalDataId)
            .Index(t => t.UserId)
            .Index(t => t.BasicMedicalData_BasicMedicalDataId)
            .Index(t => t.BasicMedicalDataId);
    }

问题就在这里-它数据库中创建附加字段BasicMedicalData_BasicMedicalDataId和延迟加载与现场忽略BasicMedicalDataId

当我把手动ID在BasicMedicalData_BasicMedicalDataId ,延迟加载带有附件的工作不错。 但我不能把这里的任何价值的代码,因为它不是一个Attachments属性..

如何解决呢? 为什么它会创建不同势名字2倍同场? 为什么延迟加载与现场BasicMedicalDataId不工作呢?

Answer 1:

你已经使用了WithMany()是配置的关系是可选过载:许多人没有在关系的另一端的导航属性-但你有关系的另一端的导航属性。

尝试这个:

   modelBuilder.Entity<Attachment>()
      //Attachment has an optional relationship with MedicalData
      .HasOptional(u => u.MedicalData)
       //It is many:optional with a navigation property named Attachments  
      .WithMany(d => d.Attachments)
      //The dependent's foreign key is BasicMedicalDataId    
      .HasForeignKey(u => u.BasicMedicalDataId);

参考: 可选WithMany方法



文章来源: EF lazy loading & fluent API creates additional field in table