InsertOrUpdate>插入确定,更新不起作用

问题描述 投票:0回答:1

[几天前,我在Entity Framework Core上尝试了AutMapper,现在我想看看InsertOrUpdate(v1.0.1)中的AutoMapper.Collection.EntityFrameworkCore是如何工作的。但是我无法使其正常工作,这是我的测试课程/设置:

DataContext(DbContext)

public class DataContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseLazyLoadingProxies(false).EnableSensitiveDataLogging(AppHelper.ShowDebugInfos).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseSqlServer(AppHelper.ConnectionString);
    }

    public DbSet<Contact> Contacts { get; set; } // with some references to other tables
}

启动

services.AddDbContext<DataContext>();

services.AddEntityFrameworkInMemoryDatabase().AddDbContext<DataContext>(); // not sure if we need this for InsertOrUpdate

services.AddAutoMapper(automapper =>
{
    automapper.AddCollectionMappers();
    automapper.UseEntityFrameworkCoreModel<DataContext>(services);
    //automapper.SetGeneratePropertyMaps<GenerateEntityFrameworkCorePrimaryKeyPropertyMaps<DataContext>>(); // exception says we have to use UseEntityFrameworkCoreModel instead of this
}, typeof(DataContext).Assembly);

AutoMapperProfile

public class AutoMapperProfile : Profile
{
    CreateMap<ContactTestDto, Contact>().ReverseMap();

    // did also try:
    //CreateMap<ContactTestDto, Contact>().EqualityComparison((source, destination) => source.Id == destination.Id);
    //CreateMap<Contact, ContactTestDto>().EqualityComparison((source, destination) => source.Id == destination.Id);
}

模型联系人

public partial class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // many more (including navigation properties)...
}

Model ContactTestDto

public partial class ContactTestDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // nothing more
}

更新

// this makes no difference:
//Contact contactFromDb = db.Contacts.Find(1); // FirstName is "John"
//db.Entry(contactFromDb).State = EntityState.Modified;

// nothing happens:
db.Contacts.Persist(mapper).InsertOrUpdate(new ContactDto { Id = 1, FirstName = "Updated Name???" });

// insert ok:
db.Contacts.Persist(mapper).InsertOrUpdate(new ContactDto { FirstName = "Inserted Name" });

db.SaveChanges();

我可以在[[both]]中看到Select-Statement(通过SQL Profiler),但是在更新中没有发送更新,插入就可以了。另外,mapper实例工作正常(我可以双向映射)。所以,我错了什么?

PS:为什么我不能写“ Hello SO-Community”?它将被缩减为“社区” oO

几天前,我尝试使用带有实体框架核心的AutMapper,现在我想看看AutoMapper.Collection.EntityFrameworkCore(v1.0.1)中的InsertOrUpdate如何工作。但我无法将其提升到...

c# entity-framework-core automapper
1个回答
0
投票
您已在数据库选项(.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking))中禁用了跟踪,因此您需要通过选项将其启用,或针对诸如此类的请求启用它:
© www.soinside.com 2019 - 2024. All rights reserved.