使AutoMapper创建新集合,而不是重用existng?

时间:2019-02-26 09:09:01

标签: .net entity-framework-core automapper

AutoMapper在映射时重用现有集合。尽管这在许多情况下可能是理想的,但在我的情况下,这会导致问题,因为EF Core不会检测到List属性已更改。 (我正在使用JSON将属性序列化为单个字符串字段)。有没有办法用AutoMapper强制创建新列表?

代码如下:

public class MyEntity
{
    public long Id {get;set;}
    public IList<string> MyStrings {get;set;} = new List<String>();
}


public class SomeOtherClass
{
    public IList<string> MyStrings {get;set;} = new List<String>();
}
AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<SomeOtherClass, MyEntity>();

        });



        using (var c = new TestContext())
        {
            Console.WriteLine("deleting database...");
            Console.WriteLine(c.Database.EnsureDeleted());
            Console.WriteLine("creating database...");
            Console.WriteLine(c.Database.EnsureCreated());
            Console.WriteLine("creating database...done.");
        }


        using (var c = new TestContext())
        {
            MyEntity e = new MyEntity();
            c.MyEntities.Add(e);
            c.SaveChanges();
        }
        using (var c = new TestContext())
        {
            MyEntity e = c.MyEntities.Single();
            SomeOtherClass other = new SomeOtherClass() {
                MyStrings = {"a string"}
            };
            AutoMapper.Mapper.Map(other, e);
            Console.WriteLine("MyStrings: " + string.Join(",",e.MyStrings)); //prints correctly
             Console.WriteLine(c.Entry(e).State); //prints Unchanged
            c.SaveChanges();
        }

        using (var c = new TestContext())
        {
            MyEntity e = c.MyEntities.Single();
            Console.WriteLine("MyStrings: " + string.Join(",",e.MyStrings)); //prints empty (because entity wasn't updated)
        }

上下文类为

public class TestContext: DbContext
{
    public void AddJsonConversion<TEntity, TProperty>(EntityTypeBuilder<TEntity> entityTypeBuilder,
        Expression<Func<TEntity, TProperty>> propertyExpression) where TEntity : class
    {
        entityTypeBuilder.Property(propertyExpression)
            .HasConversion(v => JsonConvert.SerializeObject(v),
                v => JsonConvert.DeserializeObject<TProperty>(v));

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        AddJsonConversion(modelBuilder.Entity<MyEntity>(), e => e.MyStrings);
    }
     public DbSet<MyEntity> MyEntities { get; set; }

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseMySql("server=localhost;database=mydbx;user=root;password=abc", mySqlOptions => { mySqlOptions.ServerVersion(new Version(5,7,24),ServerType.MySql); });

        }
        optionsBuilder
            .UseLazyLoadingProxies()
            .EnableSensitiveDataLogging();

        base.OnConfiguring(optionsBuilder);

    }



}

0 个答案:

没有答案