【发布时间】:2020-07-18 16:30:10
【问题描述】:
这只是一个说明性的例子,我理解这个例子中的关系本身没有意义,但它以我需要解决方案的方式绘制关系。所以请不要对此发表评论。
我正在寻找可以忽略保存导航属性的解决方案;
public class ClassRoom {
public Guid Id { get; set; }
public Guid? ClassRoomInformationId { get; set; }
public virtual ClassRoomInformation { get; set; }
public virtual Collection<Student> Students { get; set;
}
public class Student {
public Guid Id { get; set; }
public Guid? ClassRoomId { get; set; }
public Guid? StudentInformationId { get; set; }
public virtual StudentInformation { get; set; }
}
public class StudentEntityConfiguration : IEntityTypeConfiguration<Student> {
public void Configure(EntityTypeBuilder<Student> builder) {
builder.ToTable("Student");
builder.HasKey(s => s.Id);
builder.HasOne(s => s.StudentInformation)
.WithOne()
.HasForeignKey<Student>(s => s.StudentInformationId);
}
}
public class ClassRoomEntityConfiguration : IEntityTypeConfiguration<ClassRoom> {
public void Configure(EntityTypeBuilder<ClassRoom> builder) {
builder.ToTable("ClassRoom");
builder.HasKey(c => c.Id);
builder.HasOne(c => c.ClassRoomInformation)
.WithOne()
.HasForeignKey<ClassRoom>(c => c.ClassRoomInformationId);
builder.HasMany(c => c.Students)
.WithOne()
.HasForeignKey(c => c.ClassRoomInformation);
}
}
澄清我的问题(使用 EF 2.2);我想通过它自己的 StudentRepository 更新学生。当我通过 ClassRoomRepository 保存教室并且学生可能以任何方式发生变化时,我不希望该更改被保留(即使包含它以能够“查看”数据)。
我已尝试将以下内容添加到 ClassRoomEntityConfiguration:
//BeforeSaveBehavior neither works
builder.Property(c => c.Students).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
但是,这会产生以下异常: ...不能用作...上的属性,因为它被配置为导航。'
我尝试的另一件事是在教室的学生列表中设置 componentmodel 只读属性。这似乎也被忽略了。
【问题讨论】:
-
我认为主要的设计问题是您使用完整实体进行 CRUD 操作,这意味着您无法控制将输入哪些修改。排除所有存储库中的所有“非法”更改是不可行的。