EF子记录在父表中使用hasoptional

时间:2015-11-06 16:24:36

标签: c# sql-server entity-framework

我遇到的问题是,插入新的VehicleCategoryId的VehicleCategory表应该只是插入到Vehicle表的CategoryId字段中(并且它是正确的)。

同时,新的记录也会在VehicleCategory表中插入新的VehicleCategoryId,而不应该。 Vehicle表应该只使用VehicleCategory表中已有的密钥。

这是我的确认:

public class Vehicle
{
    public int VehicleId { get; set; }
    public int? CategoryId { get; set; }
    public virtual VehicleCategory VehicleCategory { get; set; }
}

public class VehicleCategory
{
    public int VehicleCategoryId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Vehicle> Vehicles { get; set; }
}

public VehicleConfiguration()
{
    this.ToTable("Vehicle");
    this.HasKey(x => x.VehicleId);
    this.HasOptional(x => x.VehicleCategory).WithMany(x => x.Vehicles).HasForeignKey(x => x.CategoryId);
}

public VehicleCategoryConfiguration()
{
    this.ToTable("VehicleCategory");
    this.HasKey(x => x.VehicleCategoryId);
}

插入位:

this.repository.Insert(Mapper.Map<Vehicle>(vehicleModel));

vehicleModel的所有属性值均来自UI表单。

0 个答案:

没有答案