【问题标题】:Entity framework with AutoMapper to handle property change, foreign key relationship gets lost使用 AutoMapper 处理属性更改的实体框架,外键关系丢失
【发布时间】: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


【解决方案1】:

您必须使用 Include 关键字急切加载驱动程序引用:

 var instance = GetDbSet().Include(s.Driver).FirstOrDefault(x => x.Id == id);

【讨论】:

  • 你应该确保对更新的实例也这样做
  • 您可能还必须显式映射驱动程序引用,而不是仅映射 id
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 2011-12-10
相关资源
最近更新 更多