这是我的代码 - 首先,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
不能很好地工作?