EF核心没有发送所有修改过的字段进行更新。

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

我正在做一个简单的更新(使用EF Core 3.1.2和SQL后台),但一直无法了解为什么有一个字段无法发送到db。

我有一个更新调用,我可以看到我要发送的DateModified的值。enter image description here

然而,使用SQL Profiler,我可以看到这就是实际被发送的内容,而且DateModified字段根本没有被发送到SQL中。

enter image description here

这里是要发送的对象

public class AVO : BasePropertiesWithID
{
    //[Authorize(Policy = "AllEmployees")]
    [ForeignKey("DivisionID")]
    public int DivisionID { get; set; }
    [Required]
    public int AccountNumber { get; set; }
    [Required]
    public string CustomerName { get; set; }
    [Required]
    public string Comments { get; set; }
    public bool IsActive { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }

    [UseFiltering]
    [UseSorting]
    public virtual Division Division { get; set; }
}

这里是包含DateModified字段(没有被发送)和DateInserted字段(正在发送)的基类。

    public class BasePropertiesWithID
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [Column(Order = 9990)]
    [DefaultValue("autoProcess")]
    public string InsertedBy { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [Required]
    [Column(Order = 9991)]
    public DateTime DateInserted { get; set; }

    [Required]
    [Column(Order = 9992)]
    [DefaultValue("autoProcess")]
    public string ModifiedBy { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [Required]
    [Column(Order = 9993)]
    public DateTime DateModified { get; set; }

}

我已经使用这个基类很长时间了,没有遇到任何问题,而且任何版本的EF都没有出现过这种情况。我一直没有成功地搜索信息,虽然我确实找到了这个。为什么EF Core Update无法更新修改后的列? 对我来说没有任何帮助。

为什么一个字段都发不出去?谁能提供WHY或如何解决?THANKS!

编辑:这个实体是如何添加到EF的enter image description hereenter image description hereenter image description hereenter image description here

.net entity-framework
1个回答
2
投票

为什么一个字段连发送都失败了?

因为你配置了属性,让它的值在添加或更新时生成。

enter image description here

这指示EF在每次更新后从数据库中重新加载该值。要应用客户端的更新,你必须要设置 SetAfterSaveBehaviorPropertySaveBehavior.Save 在模型中像这样。

modelBuilder.Entity<Person>().Property(b => b.ModifiedAt).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Save);

eg

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace EfCore3Test
{

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime ModifiedAt { get; set; }
    }

    public class Db : DbContext
    {

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Person>().Property(p => p.ModifiedAt).HasDefaultValueSql("getdate()").ValueGeneratedOnAddOrUpdate();

            modelBuilder.Entity<Person>().Property(b => b.ModifiedAt).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Save);

        }
        private static readonly ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddFilter((category, level) =>
               category == DbLoggerCategory.Database.Command.Name
               && level == LogLevel.Information).AddConsole();
        });


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLoggerFactory(loggerFactory)
                          .UseSqlServer("Server=.;database=EfCore3Test;Integrated Security=true",
                                        o => o.UseRelationalNulls());

            base.OnConfiguring(optionsBuilder);
        }
    }





    class Program
    {

        static void Main(string[] args)
        {


            using var db = new Db();

            db.Database.EnsureDeleted();
            db.Database.EnsureCreated();

            var p = new Person() { Name = "Fred" };
            db.Set<Person>().Add(p);
            db.SaveChanges();

            p.Name = "Fred2";
            p.ModifiedAt = DateTime.Now.AddDays(-7);
            db.Set<Person>().Update(p);
            db.SaveChanges();


        }
    }
  }
}

产出

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[@p2='?' (DbType = Int32), @p0='?' (DbType = DateTime2), @p1='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      UPDATE [Person] SET [ModifiedAt] = @p0, [Name] = @p1
      WHERE [Id] = @p2;
      SELECT @@ROWCOUNT;
© www.soinside.com 2019 - 2024. All rights reserved.