C# EF6对象中的AddOrUpdate对象
这就是我们所拥有的:C# EF6对象中的AddOrUpdate对象,c#,.net,entity-framework,entity-framework-6,C#,.net,Entity Framework,Entity Framework 6,这就是我们所拥有的: public class Car { public int Id { get; set; } public Engine Engine { get; set; } } public class Engine { public int Id { get; set; } public string EngineName{ get; set; } } //Map to the DB table
public class Car
{
public int Id { get; set; }
public Engine Engine { get; set; }
}
public class Engine
{
public int Id { get; set; }
public string EngineName{ get; set; }
}
//Map to the DB tables
public CarMap()
{
ToTable("CAR");
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("CAR_ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasOptional(x => x.Engine).WithMany().Map(x => x.MapKey("ENGINE"));
}
DB table CAR由int Id和int EngineID两列组成(FK到Engine table)
假设我们在car DB表中有一个现有的car对象。但是我们想要更新记录并为汽车添加一个引擎,所以我们在下面分配它
var car = new car()
{
id=1,
new Engine()
{
id=5,
EngineName="V8"
}
}
现在我们使用
carDataProvider.AddOrUpdate(car);
_unitOfWork.Commit();
但是使用我的映射的实体框架不会更新CAR表中的EngineId字段,但是如果我使用Add(CAR);然后将创建汽车记录(f.e.id=2;EngineId=99;)以及发动机记录(如果不存在)
因此,我应该改变映射,或者我如何调用AddOrUpdate(car);以便更新EngineId字段?我建议您通过以下方式配置您的模型:
public class Car
{
public int Id { get; set; }
public int EngineId { get; set; }
public Engine Engine { get; set; }
}
public class Engine
{
public int Id { get; set; }
public string EngineName{ get; set; }
}
public CarMap()
{
ToTable("CARS");
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("CAR_ID");
HasOptional(x => x.Engine).WithMany().HasForeignKey(x=>x.EngineId);
}
关系配置是这样的:
public class Car
{
public int Id { get; set; }
public int EngineId { get; set; }
public Engine Engine { get; set; }
}
public class Engine
{
public int Id { get; set; }
public string EngineName{ get; set; }
}
public CarMap()
{
ToTable("CARS");
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("CAR_ID");
HasOptional(x => x.Engine).WithMany().HasForeignKey(x=>x.EngineId);
}
正如您所看到的,我删除了您指定汽车Id为Identity的代码,您不需要这样做,这是int类型PK的默认行为。因此,如果您想自己设置引擎Id,您需要配置您的实体,如下所示:
public EngineMap()
{
ToTable("ENGINES");
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("ENGINE_ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
我不知道您的AddOrUpdate
方法的实现是什么,但我猜它应该是这样的:
public void AddOrUpdate(Car car)
{
if (car.Id == default(int)) {
// New entity
context.Cars.Add(car);
} else {
// Existing entity
context.Entry(car).State = EntityState.Modified;
}
}