3

我正在使用 .net 5 实现一个 api。我有一个学生类,它有一个地址类型的属性(根据 ddd 的值对象)。

public class Student 
{
        public long Id{ get; private set; }
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public Address Address { get; private set; }
}

public class Address
{
    public string City { get; private set; }
    public string Road { get; private set; }
}

我正在使用 fluent api 使用 ef core 5 配置数据库。

 class StudentConfiguration : IEntityTypeConfiguration<Student>
    {

        public void Configure(EntityTypeBuilder<Student> builder)
        {
            builder.ToTable("Students");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).ValueGeneratedNever().IsRequired();
            builder.Property(x => x.FirstName).HasMaxLength(25).IsRequired();
            builder.Property(x => x.LastName).HasMaxLength(50).IsRequired();           


            builder.OwnsOne(x => x.Address, x =>
            {
                x.Property(pp => pp.City)
                    .IsRequired()
                    .HasColumnName("City")
                    .HasMaxLength(20);
                x.Property(pp => pp.Road)
                    .IsRequired()
                    .HasColumnName("Road")
                    .HasMaxLength(40);
            });

        }
    }

结果,我有一个包含 Id、Fistname、lastname、city、road 列的表。

现在我试图只更新城市和道路(例如学生更衣室),但我有不同的例外,我不知道如何只更新这 2 列

public async Task UpdateAddress(Student student)
{
//Firts try 
            //var studentEntry = context.Entry(student);
            //studentEntry.Property(x => x.Address.City).IsModified = true;
            //studentEntry.Property(x => x.Address.Road).IsModified = true;
            //**Exception** 'The expression 'x => x.Address.City' is not a valid member access expression. The expression should represent a simple property or field access: 't => t.MyProperty'. (Parameter 'memberAccessExpression')'

//Second try 
             //var studentEntry = context.Entry(student.Address);
            //studentEntry.Property(x => x.City).IsModified = true;
            //studentEntry.Property(x => x.Road).IsModified = true;
            //**Exception** 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. 

//the only method that works is Update but this update the whole object
     context.Update(student);
     await context.SaveChangesAsync();
}

编辑

public class StudentDbContext : DbContext
    {
        public DbSet<Student> Students { get; set; }

        public StudentDbContext(DbContextOptions<StudentDbContext> options) : base(options)
        {
            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
            base.OnModelCreating(modelBuilder);
        }
    }

如何只更新拥有实体的这两个属性?

4

2 回答 2

5

Address拥有的实体类型,因此Student.AddressEF Core 术语中的属性不是属性,而是引用导航属性,因此应该通过Reference方法而不是Property方法访问​​(它们都不支持属性路径)。然后您可以使用返回的跟踪条目来访问其成员。

要强制更新 的某些属性Student.Address,首先附加Student实体实例(告诉 EF 它存在)

var studentEntry = context.Attach(student);

然后使用这样的东西

var addressEntry = studentEntry.Reference(e => e.Address);
addressEntry.TargetEntry.Property(e => e.City).IsModified = true;
addressEntry.TargetEntry.Property(e => e.Road).IsModified = true;

于 2021-03-26T13:57:59.463 回答
-1

由于 EntityFramework 不跟踪您的查询(因为您在 DBContext 配置中设置了它),您可以尝试以下流程:

首先通过其 ID 从 DB 获取学生,然后仅更改您想直接在该实体上更改的那两个属性。

public async Task UpdateAddress(Student student)
{
    // Get existing student by its ID from the database
    var existingStudent = await context.Students
        .Include(x => x.Address)
        .SingleOrDefaultAsync(x => x.Id == student.Id);

    // To prevent null reference exception
    if (existingStudent is null)
        return; // Exception maybe? Depends on your app flow

    // Edit address value object with the method available in your entity, since you're using DDD approach
    existingStudent.ChangeAddress(student.Address);

    // Since your query are not tracked you need to explicity tell EF that this entry is being modified
    context.Entry(existingStudent).State = EntityState.Modified;

    // EF will save only two properties in that case
    await context.SaveChangesAsync();
}

比在您的Student实体类中添加以下方法以提供更改其地址的能力:

public void ChangeAddress(Address newAddress)
{
    // Some additional conditions to check the newAddress for nulls, valid values, etc.

    Address = newAddress;
}

您可以将您的地址视为一个值对象并将其替换为新的地址 VO。

于 2021-03-26T09:57:37.727 回答