这里是我的代码-首先, 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
不工作呢?