我正在努力连接两个非常简单的表:
[Table("Item")]
public class Item
{
[Key]
[Column("itemId", TypeName = "int")]
public int ItemId { get; set; }
}
[Table("LinkedItems")]
public class LinkedItem
{
[Key]
[Column("itemId", TypeName = "int")]
public int ItemId { get; set; }
[Column("parentItemId", TypeName = "int")]
public int ParentItemId { get; set; }
}
LinkedItem
表格中有两个外键:
itemId
,指向表格Item
以展示自己
parentItemId
,指向表Item
以显示其父级
我想做到这样的事情:
[Table("Item")]
public class Item
{
[Key]
[Column("itemId", TypeName = "int")]
public int ItemId { get; set; }
public ICollection<LinkedItem> ChildItems { get; set; }
public LinkedItem LinkedItem { get; set; }
}
[Table("LinkedItems")]
public class LinkedItem
{
[Key]
[Column("itemId", TypeName = "int")]
public int ItemId { get; set; }
[Column("parentItemId", TypeName = "int")]
public int ParentItemId { get; set; }
public Item Item { get; set; }
public Item ParentItem { get; set; }
}
我成功创建了从Item到LinkedItem的连接:
modelBuilder.Entity<Item>().HasOptional(i => i.LinkedItem).WithRequired(i => i.Item);
但我无法添加其他连接。你能帮我解决这两个表的Fluent API配置吗?
答案 0 :(得分:3)
此类不需要LinkedItem类。你可以用一个类完成这个任务。
public class Item
{
public int Id { get; set; }
public int ParentItemId { get; set; }
public virtual Item ParentItem { get; set; }
public virtual ICollection<Item> ChildItems { get; set; }
}
modelBuilder.Entity<Item>()
.HasRequired(entity => entity.ParentItem)
.WithMany(entity => entity.ChildItems)
.HasForeignKey(entity => entity.ParentItemId);
否则只需添加:
modelBuilder.Entity<Item>()
.HasMany(entity => entity.ChildItems)
.WithRequired(entity => entity.ParentItem)
.HasForeignKey(entity => entity.ParentItemId);
编辑:延长答案。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Item>()
.HasOptional(entity => entity.LinkedItem)
.WithRequired(entity => entity.Item);
modelBuilder.Entity<Item>()
.HasMany(entity => entity.ChildItems)
.WithRequired(entity => entity.ParentItem)
.HasForeignKey(entity => entity.ParentItemId);
}
[Table("Item")]
public class Item
{
[Key]
public int ItemId { get; set; }
public virtual ICollection<LinkedItem> ChildItems { get; set; }
public virtual LinkedItem LinkedItem { get; set; }
}
[Table("LinkedItem")]
public class LinkedItem
{
[Key]
public int ItemId { get; set; }
public int ParentItemId { get; set; }
public virtual Item Item { get; set; }
public virtual Item ParentItem { get; set; }
}