实体框架忽略我的外键并创建自己的外键。我怎么能解决这个问题?
我的课程很少:
[Table("Entity")]
public class Entity
{
public Entity()
{
HeavyEntities = new List<HeavyEntity>();
}
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntityId { get; set; }
public string Name { get; set; }
public ICollection<HeavyEntity> HeavyEntities { get; set; }
}
[Table("HeavyEntity")]
public class HeavyEntity
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntityHeavyId { get; set; }
public int EntityId { get; set; }
public virtual Entity Entity { get; set; }
public int? TargetEntityId { get; set; }
public virtual Entity TargetEntity { get; set; }
public Relation Relation { get; set; }
}
[Table("Tech")]
public class Tech : Entity
{
public string Status { get; set; }
}
[Table("Company")]
public class Company : Entity
{
public string Country { get; set; }
}
创建并保存实体:
var (context = new MyDbContex())
{
var tech = new Tech
{
Name = "Tech1",
Status = "New",
};
var company = new Company
{
Name = "Company1",
Country = "Ukraine"
};
tech.HeavyEntities.Add(new HeavyEntity
{
Relation = Relation.AsParent,
TargetEntity = company,
});
context.Techs.Add(tech);
context.Companies.Add(company);
context.SaveChanges();
}
对于此类,Entity Framework创建下表(HeavyEntity):
如何将外键映射到我的字段?
解决:
[Table("Entity")]
public class Entity
{
public Entity()
{
HeavyEntities = new List<HeavyEntity>();
}
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntityId { get; set; }
public string Name { get; set; }
[InverseProperty("Entity")]
public ICollection<HeavyEntity> HeavyEntities { get; set; }
}
[Table("HeavyEntity")]
public class HeavyEntity
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntityHeavyId { get; set; }
[ForeignKey("EntityId")]
public int EntityId { get; set; }
public virtual Entity Entity { get; set; }
[ForeignKey("TargetEntityId")]
public int? TargetEntityId { get; set; }
public virtual Entity TargetEntity { get; set; }
public Relation Relation { get; set; }
}
答案 0 :(得分:1)
添加ForeignKey属性。
请参阅https://msdn.microsoft.com/en-us/data/jj591583#Relationships
[Table("HeavyEntity")]
public class HeavyEntity
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntityHeavyId { get; set; }
public int EntityId { get; set; }
public virtual Entity Entity { get; set; }
public int? TargetEntityId { get; set; }
[ForeignKey("TargetEntityId")] // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public virtual Entity TargetEntity { get; set; }
public Relation Relation { get; set; }
}