Reputation: 419
This is what we have:
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 consists of two columns of int Id and int EngineID (FK to the Engine table)
So let's say we have an existing a car object in the Car DB table. But we want to update the record and add an engine for the car, so we assign it below.
var car = new car()
{
id=1,
new Engine()
{
id=5,
EngineName="V8"
}
}
And now we use
carDataProvider.AddOrUpdate(car);
_unitOfWork.Commit();
but the entity framework using my mapping doesn't update the EngineId field in the CAR table, however if I would use Add(car); then car record would be created(f.e. id=2; EngineId=99;) as well as Engine record(if doesn't exist).
So should I change the mapping or how else could I call AddOrUpdate(car); so that the EngineId field would be updated?
Upvotes: 1
Views: 403
Reputation: 39376
I recommend you configure your model this way:
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; }
}
And the relationship configuration would be this way:
public CarMap()
{
ToTable("CARS");
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("CAR_ID");
HasOptional(x => x.Engine).WithMany().HasForeignKey(x=>x.EngineId);
}
As you can see I delete the code where you are specifying the Car Id is Identity, you don't need to do that, that is the default behavior for PK of type int. So, if you want to set the Engine Id by yourself, you need to configure your entity as I show below:
public EngineMap()
{
ToTable("ENGINES");
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("ENGINE_ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
I don't know what is the implementation of your AddOrUpdate
method but I guess it would be something like this:
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;
}
}
Upvotes: 3