1

这是我的代码 - 首先,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并在延迟加载时忽略了 field BasicMedicalDataId

当我手动输入 ID 时BasicMedicalData_BasicMedicalDataId,带有附件的延迟加载效果很好。但是我不能在这里用代码输入任何值,因为它不是Attachments属性..

如何解决?为什么它会创建 2 个具有不同名称的相同字段?为什么延迟加载字段BasicMedicalDataId不能很好地工作?

4

1 回答 1

0

您使用了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方法

于 2013-10-29T09:38:06.607 回答