Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动映射外键_C#_Entity Framework_Asp.net Web Api - Fatal编程技术网

C# 自动映射外键

C# 自动映射外键,c#,entity-framework,asp.net-web-api,C#,Entity Framework,Asp.net Web Api,我在WebApi2项目中使用Automapper和CodeFirstEF6。我的模型类是POCO,每个模型类都有一个EntityTypeConfiguration类 我也有DTO课程。这些类不公开外键属性,我告诉Automapper忽略外键 例如: public partial class UserGroupModel { public UserGroupModel() { this.Users = new List<UserGroupUserModel&g

我在WebApi2项目中使用Automapper和CodeFirstEF6。我的模型类是POCO,每个模型类都有一个
EntityTypeConfiguration

我也有DTO课程。这些类不公开外键属性,我告诉Automapper忽略外键

例如:

public partial class UserGroupModel
{
    public UserGroupModel()
    {
        this.Users = new List<UserGroupUserModel>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<UserGroupUserModel> Users { get; set; }
}

public partial class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public partial class UserGroupUserModel
{
    public int Id { get; set; }
    public int UserGroupId { get; set; }
    public int UserId { get; set; }
    public virtual UserGroupModel { get; set; }
    public virtual UserModel { get; set; }
}
由于实体在从DTO映射到模型时被分离,并且由于DTO类没有外键属性(在本例中为
UserGroupId
UserId
),这些属性的值始终为0。因此,在调用
SaveChanges
之前,我必须执行以下操作:

public override UserGroupModel Update(UserGroupModel entity)
{
    entity.Users.ToList()
                .ForEach(x => {
                    x.UserGroupId = entity.Id;
                    x.UserId = x.User.Id;
                });

    //Update db here...
}
是否有更好的方法来处理这种情况?注释属性是否会创建更清晰的代码

public override UserGroupModel Update(UserGroupModel entity)
{
    entity.Users.ToList()
                .ForEach(x => {
                    x.UserGroupId = entity.Id;
                    x.UserId = x.User.Id;
                });

    //Update db here...
}