将实体框架导航属性映射到ViewModel对象

时间:2016-03-30 18:58:02

标签: c# wpf entity-framework mvvm orm

我使用Entity Framework 6在Visual Studio 2015中构建一个WPF MVVM Light应用程序,并使用数据库优先模型生成。我为我的模型创建View Model类以与我的Views(用户控件)一起使用。

我有以下三种EF型号; Employee可以有多个EmployeeStatuEmployeeStatu有相应的description(&#39;缺席&#39;,&#39;已存档&#39;,在ValidEmployeeStatu模型上。因此,employeeID上的EmployeeStatu为FK,而validEmployeeStatusID上的EmployeeStatuValidEmployeeStatu上的FK(public partial class Employee { public Employee() { this.EmployeeStatus = new HashSet<EmployeeStatu>(); } public int employeeID { get; set; } // More properties here... public virtual ICollection<EmployeeStatu> EmployeeStatus { get; set; } } public partial class EmployeeStatu { public int employeeStatusID { get; set; } public int employeeID { get; set; } public int validEmployeeStatusID { get; set; } // More properties here... public virtual Employee Employee { get; set; } public virtual ValidEmployeeStatu ValidEmployeeStatu { get; set; } } public partial class ValidEmployeeStatu { public ValidEmployeeStatu() { this.EmployeeStatus = new HashSet<EmployeeStatu>(); } public int validEmployeeStatusID { get; set; } public string description { get; set; } // More properties here... public virtual ICollection<EmployeeStatu> EmployeeStatus { get; set; } } 上的PK)。

public class EmployeeViewModel : ViewModelBase
{
    private int _employeeId;
    private string _securityId;
    private IEnumerable<EmployeeStatusViewModel> _employeeStatus;

    public EmployeeViewModel ()
    {
        this.EmployeeStatusVMs = new HashSet<EmployeeStatusViewModel>();
    }

    public IEnumerable<EmployeeStatusViewModel> EmployeeStatusVMs
    {
        get { return _employeeStatus; }
        set
        {
            if (_employeeStatus.Equals(value)) return;
            _employeeStatus = value; 
            RaisePropertyChanged();
        }
    }

    // More properties here...
}   

这是我的员工视图模型;其他人遵循相同的模式:

var query = (from e in Context.Employees
             .Include("EmployeeStatus.ValidEmployeeStatu")
             .Where(comparison)
             select new EmployeeViewModel
             {
                 employeeID = e.employeeID,
                 securityID = e.securityID,
                 firstName = e.firstName,
                 middleName = e.middleName,
                 lastName = e.lastName,
                 suffix = e.suffix,
                 job = e.job,
                 organizationalUnit = e.organizationalUnit,
                 costCenter = e.costCenter,
                 notes = e.notes,
                 createdDate = e.createdDate
             });

我正在使用此LINQ查询来获取数据:

EmployeeStatu

如何将导航属性ValidEmployeeStatuSaveChanges()映射到我的View模型?那么如何从{{1}}的视图模型对象中将值返回到模型?谢谢。

1 个答案:

答案 0 :(得分:1)

您应该在第一级模型中执行相同的操作。因此,在您的EmployeeViewModel创建中,请执行以下操作:

employeeStatus = e.EmployeeStatus.Select(s=>new EmployeeStatusViewModel{...}.ToList()

当回到模型相同类型的映射但从ViewModel到Model时。 或者你可以检查自动化器。搜索博客。