我想使用实体框架将一些 JSON 数据存储到数据库中。
这是我的 JSON:
{
"BrandId": 488,
"PropDetail": {
"LicenceNumber": "123",
"InsuranceNumber": "456",
"PostalCode": "4AN"
},
"Drivers": [
{
"Id": 2,
"LicenceNumber": "123",
"InsuranceNumber": "456",
"PostalCode": "4AN"
}
]
}
JSON 中会有多个驱动程序详细信息。
保存的数据应该是这样的:
这是我的表格结构:
Id, BrandId, PropDetail, DriversDetail
我正在尝试保存数据以及从请求到实体类的映射。
我的实体类如下:
public class DriverInfo : IdEntityBase
{
public virtual int DriverInfoId { get; set; }
public virtual int BrandId { get; set; }
public virtual ProposerDetails PropDetails { get; set; }
public virtual IEnumerable<DriverDetails> DriverDetails { get; set; }
}
var driverInfo = new DriverInfo()
{
BrandId = request.BrandId,
ProposerDetails = new ProposerDetails()
{
DriverId = 1,
PostalCode = request.PropDetail.PostalCode,
LicenceNumber = request.PropDetail.LicenceNumber,
InsuranceNumber = request.PropDetail.InsuranceNumber
},
DriverDetails = request.Drivers.Select(x => new DriverDetails()
{
DriverId = x.Id,
LicenceNumber = x.LicenceNumber,
InsuranceNumber = x.NationalInsuranceNumber,
PostalCode = x.PostalCode
})
};
Repository.Save(driverInfo);
我将实体的
DbSet
添加到我的 Dbcontext
:
public DbSet<DriverInfo> DriverInfo { get; set; }
当我尝试保存数据时,出现以下异常:
实体类型“DriverInfo”上的导航属性“DriverDetails”的类型是“SelectListIterator
”,它不实现 ICollection
尝试使用
ICollection
作为导航属性:
public ICollection<DriverDetails> DriverDetails { get; set; }
并在保存数据之前使用
ToList()
,例如:
DriverDetails = request.Drivers.Select(x => new DriverDetails()
{
DriverId = x.Id,
LicenceNumber = x.LicenceNumber,
InsuranceNumber = x.NationalInsuranceNumber,
PostalCode = x.PostalCode
}) .ToList()