3

考虑这个简单的模型和视图模型场景:

public class SomeModel
{
    public virtual Company company {get; set;}
    public string name {get; set;}
    public string address {get; set;}

    //some other few tens of properties
}

public class SomeViewModel
{
    public Company company {get; set;}
    public string name {get; set;}
    public string address {get; set;}
    //some other few tens of properties
}

出现的问题是:

我有一个不需要公司的编辑页面,所以我不从数据库中获取它。现在,当提交表单时,我会:

SomeModel destinationModel = someContext.SomeModel.Include("Company").Where( i => i.Id == id) // assume id is available from somewhere.

然后我做一个

Company oldCompany = destinationModel.company; // save it before mapper assigns it null

Mapper.Map(sourceViewModel,destinationModel);

//After this piece of line my company in destinationModel will be null because sourceViewModel's company is null. Great!!
//so I assign old company to it

destinationModel.company = oldCompany;

context.Entry(destinationModel).State = EntityState.Modified;

context.SaveChanges();

问题是即使我将 oldCompany 分配给我的公司,在 savechanges 之后它在数据库中仍然为空。

笔记:

如果我更改这些行:

destinationModel.company = oldCompany;

context.Entry(destinationModel).State = EntityState.Modified;

context.SaveChanges();

对这些:

context.Entry(destinationModel).State = EntityState.Modified;

destinationModel.company = oldCompany;

context.Entry(destinationModel).State = EntityState.Modified;

context.SaveChanges();

请注意,我更改了 2 次状态,它工作正常。可能是什么问题?这是 ef 4.1 的错误吗?

这是解决该问题的示例控制台应用程序:

using System;
using System.Linq;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using AutoMapper;

namespace Slauma
{
    public class SlaumaContext : DbContext
    {
        public DbSet<Company> Companies { get; set; }
        public DbSet<MyModel> MyModels { get; set; }

        public SlaumaContext()
        {
            this.Configuration.AutoDetectChangesEnabled = true;
            this.Configuration.LazyLoadingEnabled = true;
        }
    }

    public class MyModel
    {
        public int Id { get; set; }
        public string Foo { get; set; }

        [ForeignKey("CompanyId")]
        public virtual Company Company { get; set; }

        public int? CompanyId { get; set; }
    }

    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


    public class MyViewModel
    {
        public string Foo { get; set; }

        public Company Company { get; set; }

        public int? CompanyId { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer<SlaumaContext>(new DropCreateDatabaseIfModelChanges<SlaumaContext>());

            SlaumaContext slaumaContext = new SlaumaContext();

            Company company = new Company { Name = "Microsoft" };
            MyModel myModel = new MyModel { Company = company, Foo = "Foo"};

            slaumaContext.Companies.Add(company);
            slaumaContext.MyModels.Add(myModel);
            slaumaContext.SaveChanges();

            Mapper.CreateMap<MyModel, MyViewModel>();
            Mapper.CreateMap<MyViewModel, MyModel>();


            //fetch the company
            MyModel dest = slaumaContext.MyModels.Include("Company").Where( c => c.Id == 1).First(); //hardcoded for demo

            Company oldCompany = dest.Company;

            //creating a viewmodel
            MyViewModel source = new MyViewModel();
            source.Company = null;
            source.CompanyId = null;
            source.Foo = "foo hoo";

            Mapper.Map(source, dest); // company null in dest


            //uncomment this line then only it will work else it won't is this bug?
            //slaumaContext.Entry(dest).State = System.Data.EntityState.Modified; 

            dest.Company = oldCompany;

            slaumaContext.Entry(dest).State = System.Data.EntityState.Modified;
            slaumaContext.SaveChanges();

            Console.ReadKey();

        }
    }
}
4

2 回答 2

3

默认情况下,Automapper 总是将每个属性从源实例更新到目标实例。因此,如果您不希望您的 Company 属性被覆盖,那么您必须为您的映射器显式配置它:

Mapper.CreateMap<MyViewModel, MyModel>().ForMember(m => m.Company, c => c.UseDestinationValue());

到目前为止,没有任何与 EF 相关的内容。但是,如果您将其与 EF 一起使用,则必须一致地使用导航属性 Company 和 CompanyId:您还需要在映射期间使用 CompanyId 的目标值:

Mapper.CreateMap<MyViewModel, MyModel>().ForMember(m => m.CompanyId, c => c.UseDestinationValue());

编辑:但问题不在于您的公司为空,而是在重置后它在数据库中仍然为空。这是由于如果您拥有像“CompanyId”这样的显式 Id 属性,则必须维护它。所以打电话是不够的,destinationModel.company = oldCompany;你还需要打电话destinationModel.companyId = oldCompany.Id;

并且因为您从上下文中检索了目标实体,它已经在为您进行更改跟踪,因此无需设置 EntityState.Modified。

编辑:您修改后的样本:

Mapper.CreateMap<MyModel, MyViewModel>();
Mapper.CreateMap<MyViewModel, MyModel>();    

//fetch the company 
MyModel dest = slaumaContext.MyModels.Include("Company").Where(c => c.Id == 18).First(); //hardcoded for demo 

var oldCompany = dest.Company;

//creating a viewmodel 
MyViewModel source = new MyViewModel();
source.Company = null;
source.CompanyId = null;
source.Foo = "fdsfdf";

Mapper.Map(source, dest); // company null in dest 

dest.Company = oldCompany;
dest.CompanyId = oldCompany.Id;

slaumaContext.SaveChanges();
于 2011-10-19T12:46:15.940 回答
2

在我看来,@nemesv 的答案中的第二个编辑或 AutoMapper 的微调是要走的路。你应该接受他的回答。我只添加解释为什么您的代码不起作用(但是您的代码设置了两次状态)。首先,问题与 AutoMapper 无关,当您手动设置属性时,您将获得相同的行为。

要知道的重要一点是,设置状态 ( Entry(dest).State = EntityState.Modified) 不仅会在上下文中设置一些内部标志,而且State调用的属性设置器实际上是一些复杂的方法,尤其是它调用DbContext.ChangeTracker.DetectChanges()(如果你不禁用AutoDetectChangesEnabled)。

那么,在第一种情况下会发生什么:

// ...
Mapper.Map(source, dest);
dest.Company = oldCompany;

// at this point the state of dest EF knows about is still the state
// when you loaded the entity from the context because you are not working
// with change tracking proxies, so the values are at this point:
// dest.CompanyId = null    <- this changed compared to original value
// dest.Company = company   <- this did NOT change compared to original value

// The next line will call DetectChanges() internally: EF will compare the
// current property values of dest with the snapshot of the values it had
// when you loaded the entity
slaumaContext.Entry(dest).State = System.Data.EntityState.Modified;

// So what did EF detect:
// dest.Company didn't change, but dest.CompanyId did!
// So, it assumes that you have set the FK property to null and want
// to null out the relationship. As a consequence, EF also sets dest.Company
// to null at this point and later saves null to the DB

第二种情况会发生什么:

// ...
Mapper.Map(source, dest);

// Again in the next line DetectChanges() is called, but now
// dest.Company is null. So EF will detect a change of the navigation property
// compared to the original state
slaumaContext.Entry(dest).State = System.Data.EntityState.Modified;

dest.Company = oldCompany;

// Now DetectChanges() will find that dest.Company has changed again
// compared to the last call of DetectChanges. As a consequence it will
// set dest.CompanyId to the correct value of dest.Company
slaumaContext.Entry(dest).State = System.Data.EntityState.Modified;

// dest.Company and dest.CompanyId will have the old values now
// and SaveChanges() doesn't null out the relationship

因此,这实际上是正常的更改跟踪行为,而不是 EF 中的错误。

我发现令人不安的一件事是,您有一个 ViewModel,它显然具有您未在视图中使用的属性。如果您的 ViewModel 没有CompanyCompanyId那么所有的麻烦都会消失。(或者至少配置 AutoMapper 以不映射这些属性,如 @nemesv 所示。)

于 2011-10-19T15:09:11.687 回答