[英]Update is not working in OwnsMany Value Object relationship EF Core 5
[英]How to update many owned entities with OwnsMany relationship in EF core
我正在使用域驱动设计在 .net 5 和 ef core 5 中实现 web api。 问题是:我有一个简单的汇总学生和一个值 object 类似的电话
public class Student
{
public long Id{ get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public IReadOnlyCollection<Phone> Phones { get; private set; }
}
public class Phone
{
public string Key { get; private set; }
public string Value { get; private set; }
}
它是如何工作的,例如一个学生有两部手机,价值为 123345 的钥匙手机和价值为 2345678 的钥匙手机等
我正在使用 fluent api 来配置这种关系
class StudentConfiguration : IEntityTypeConfiguration<Student>
{
public const string StudentId = "StudentId";
public const string Key = "Key";
public void Configure(EntityTypeBuilder<Student> builder)
{
builder.ToTable("StudentsDB");
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.OwnsMany(
x => x.Phones,
builder =>
{
builder.ToTable("Phones");
builder.Property<long>(StudentId).IsRequired();
builder.WithOwner().HasForeignKey(StudentId);
builder.Property(x => x.Key).IsRequired();
builder.Property(x => x.Value).IsRequired();
builder.HasKey(StudentId, Key);
});
}
}
现在的问题是,我的业务要求是让学生能够更换全部或一部手机(如果学生更换一部手机,我考虑的最简单的方法,在我的 api 内部更换两部手机,一部新值和另一个旧值)
但现在我不知道如何实现这一点......更新方法更新整个学生实体,当我尝试调用集合 aw 导航时,我不知道如何继续......
public async Task UpdatePhones(Student student)
{
#warning must fix it , it update the whole entity
//var studentEntry = context.Attach(student);
context.Update(modification.Student);
//var phoneEntries = studentEntry.Collection(e => e.Phones);
//phoneEntries.IsModified = true;
await context.SaveChangesAsync();
}
注意:我考虑的最简单方法是学生更换一部手机,在我的 api 内部更换两部手机,一部用新值,另一部用旧值
您可以尝试使用以下代码
var s1= await _context.Students.Where(x => x.Id == student.Id).SingleAsync();
s1.Phones = student.Phones;
_context.Update(s1);
await _context.SaveChangesAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.