如何将种子数据添加到DbSet
并将其与另一个DbSet
记录绑定?
对于我的解决方案,ForeignKey
的值已正确设置,但TypeModel
中的ObjectModel
始终为null
。另外,在创建ICollection
之后如何将对象添加到ObjectTypeModel
中,还是可以从EF Core中自动填充对象?
我的模特:
public class ObjectModel : BaseEntity
{
[Key]
public int Id { get; set;
public String Name { get; set; }
public String PreviewImage { get; set; }
public String TagName { get; set; }
// Foreign keys---
public int TypeId { get; set; }
public ObjectTypeModel TypeModel { get; set; }
//---
}
public class ObjectTypeModel : BaseEntity
{
[Key]
public int TypeModelId { get; set; }
public String Name { get; set; }
public String PreviewImage { get; set; }
public String TagName { get; set; }
public ICollection<ObjectModel> Objects { get; set; }
}
我的OnModelCreating()
中的DbContext
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ObjectModel>()
.HasOne<ObjectTypeModel>(d => d.TypeModel)
.WithMany(dm => dm.Objects)
.HasForeignKey(dkey => dkey.TypeId);
}
我的播种数据方法:
context.Set<ObjectTypeModel>().AddRange(new ObjectTypeModel[]
{
new ObjectTypeModel()
{
TypeModelId = 1,
Name = "TestType",
PreviewImage = null,
TagName = "TestType"
}
});
context.SaveChangesAsync();
var objectTypeOne = context.ObjectTypes.SingleOrDefault(a => a.TypeModelId.Equals(1));
context.Set<ObjectModel>().Add(new ObjectModel
{
new ObjectModel() { Name="Test", PreviewImage = "null", TagName = "Test", TypeId = objectTypeOne.TypeModelId, TypeModel = objectTypeOne }
});
context.SaveChangesAsync();
尝试接收数据时的输出,其中TypeModel始终为null
。
{“ id”:1,“ name”:“ Test”,“ previewImage”:“ null”,“ tagName”:“ Test”,“ typeId”:1,“ typeModel”:null,“ createdOn”: “ 2020-06-29T23:01:24.744472”,“ modifiedOn”:“ 2020-06-29T23:01:24.744464”}
答案 0 :(得分:0)
它不能自动填充,这就是为什么typeModel
在接收数据时为空。
您需要组装ObjectModel
。
详细信息:
执行SaveChangesAsync
时,只有[Name="Test", PreviewImage = "null", TagName = "Test", TypeId = objectTypeOne.TypeModelId
]保存在数据库中。
context.Set<ObjectModel>().Add(new ObjectModel
{
new ObjectModel() { Name="Test", PreviewImage = "null", TagName = "Test", TypeId = objectTypeOne.TypeModelId, TypeModel = objectTypeOne }
});
context.SaveChangesAsync();
在返回ObjectModel.TypeModel
之前,将ObjectModel.TypeModelId
设置为ObjectModel
。
public IActionResult GetObjectModel(int? id)
{
if (id == null)
{
return NotFound();
}
var objectModel= await _context.ObjectModel.FindAsync(id);
if (objectModel== null)
{
return NotFound();
}
var typeModel= await _context.TypeModel.FindAsync(objectModel.TypeModelId);
if (typeModel!= null)
objectModel.TypeModel = typeModel;
return View(objectModel);
}