【发布时间】:2018-08-17 04:51:48
【问题描述】:
我正在使用 AutoMapper 将我更新的模型映射到实体。我面临的问题是,当我更改学生对象的属性时,例如:IsPressent,在更新方法之后,Driver 引用变为空。我认为我在更新方法上做错了。感谢任何帮助或提示。
学生班:
public class Student
{
[Key]
public int Id { get; set; }
public bool IsPressent { get; set; }
/// <summary>
/// Optional
/// </summary>
public int? DriverRefId { get; set; }
[ForeignKey("DriverRefId")]
public Driver Driver { get; set; }
}
驱动类:
public class Driver
{
[Key]
public int Id { get; set; }
public List<Student> Students { get; set; }
public bool IsPressent { get; set; }
}
映射器配置文件:
public class StudentProfile : Profile
{
public StudentProfile()
{
CreateMap<Student, Student>()
.ForMember(x => x.Id, opt => opt.Ignore())
.ForMember(x => x.DriverRefId, opt =>
{
// If driver is not null
opt.Condition(x => x.Driver != null);
opt.MapFrom(x => x.Driver.Id);
});
}
}
更新方法:
/// <summary>
/// Updates entity given the id and instance
/// </summary>
/// <param name="id"></param>
/// <param name="updatedInstance"></param>
/// <returns></returns>
public virtual T Update(int id, T updatedInstance)
{
var instance = GetDbSet().FirstOrDefault(x => x.Id == id);
if (instance != null)
{
instance = GetMapper().Map(updatedInstance, instance);
GetDbSet().Update(instance);
GetDbContext().SaveChanges();
return updatedInstance;
}
return null;
}
【问题讨论】:
-
您是否尝试手动将实例映射到实体类型?
标签: c# entity-framework .net-core automapper