Entity framework 添加实体而不获取
具有下列实体:Entity framework 添加实体而不获取,entity-framework,entity-framework-core,Entity Framework,Entity Framework Core,具有下列实体: [Table("School")] public class SchoolEntity { public SchoolEntity() { Students = new HashSet<StudentEntity>(); } [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid Id { get; set; } [For
[Table("School")]
public class SchoolEntity
{
public SchoolEntity()
{
Students = new HashSet<StudentEntity>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
[ForeignKey("SchoolId")]
public virtual ICollection<StudentEntity> Students { get; set; }
}
[Table("Student")]
public class StudentEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
[Required]
public SchoolEntity School { get; set; }
}
modelBuilder.Entity<SchoolEntity>()
.HasMany(e => e.Students)
.WithOne(e => e.School)
.IsRequired();
如何在不检索家长的情况下添加新学生,我尝试了各种组合,但没有插入学生:
public async Task AddAsync(IList<ParameterDataEntity> entities, Guid schoolId, CancellationToken token)
{
var school = new School { Id = schoolId };
DbContext.Schools.Attach(school);
foreach (var entity in entities)
{
entity.School = school;
DbContext.Students.Add(entity);
DbContext.Entry(entity).State = EntityState.Added;
}
await DbContext.SaveChangesAsync(token);
}
public async Task AddAsync(IList<ParameterDataEntity> entities, Guid schoolId, CancellationToken token)
{
var school = new School { Id = schoolId };
DbContext.Schools.Attach(school);
foreach (var entity in entities)
{
entity.School = school;
DbContext.Students.Add(entity);
}
await DbContext.SaveChangesAsync(token);
}
谢谢尝试在StudentEntity中添加SchoolEntityId属性,并在添加学生时分配该属性
[Table("Student")]
public class StudentEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public Guid SchoolEntityId {get; set; }
[Required]
public SchoolEntity School { get; set; }
}
以及:
public async Task AddAsync(IList<ParameterDataEntity> entities, Guid schoolId, CancellationToken token)
{
foreach (var entity in entities)
{
entity.SchoolEntityId = schoolId;
DbContext.Students.Add(entity);
}
await DbContext.SaveChangesAsync(token);
}