我刚刚获得EF的支持,但我刚遇到一个问题,我想知道是否有人可以提供帮助:
我有两个这样的模型:
public class Car
{
public int Id {get; set;}
public string Manufacturer {get; set;}
public string City {get;set;}
}
public class CarInfo
{
public int Id {get; set;}
public int CarId {get; set;}
public string Colour {get;set;}
public string Variant {get;set;}
public virtual Car Car {get;set;}
}
我在汽车表中插入数据如下:
int id = 0;
var _car = new Car()
{
Manufacturer = "BMW",
City = "London"
};
db.Add(_car);
db.SaveChanges();
id = _car.Id;
然后现在我正在尝试将数据保存到CarInfo表中,如下所示:
CarContext db = new CarContext();
var _carInfo = new CarInfo()
{
CarId = id,
Colour = "Blue",
Variant = "Sport"
};
db.Add(_carInfo) //I'm getting an error here (red line under code) error: Cannot Convert from CarInfo to Car.
我错过了什么?或者甚至可以使用Entity Framework实现这一目标吗?
答案 0 :(得分:3)
请在CarContext课程中告诉我你的DbSet属性,它应该是
public DbSet<Car> Cars { get; set; }
public DbSet<CarInfo> CarInfos { get; set;}
EF Add方法应该是这样的:
db.Cars.Add(_car);
和
db.CarInfos.Add(_carInfo);