我将更新中间表中的schooltypeid,这是我的存储库类。
public async Task UpdateSchoolsAsync(SchoolUpdateVm schoolUpdateVm)
{
if (_GpsContext != null)
{
var schoolsObj = _GpsContext.School.FirstOrDefault(x => x.ID == Guid.Parse(schoolUpdateVm.id));
var schoolTypeObj = _GpsContext.SchoolsSchoolTypes.FirstOrDefault(x => x.SchoolTypeId == Guid.Parse(schoolUpdateVm.schoolTypeId));
Schools schools = new Schools();
{
schoolsObj.Name = schoolUpdateVm.name;
schoolsObj.Email = schoolUpdateVm.email;
schoolsObj.Phone = schoolUpdateVm.phone;
schoolsObj.Description = schoolUpdateVm.description;
schoolsObj.StateID = Guid.Parse(schoolUpdateVm.stateID);
schoolsObj.CountryId = Guid.Parse(schoolUpdateVm.countryId);
schoolTypeObj.SchoolTypeId = Guid.Parse(schoolUpdateVm.schoolTypeId); //here i can`t update schoolYype
}
_GpsContext.School.Update(schoolsObj);
await _GpsContext.SaveChangesAsync();
}
}
这是我在实体框架中的School表:
public partial class Schools
{
public Guid ID { get; set; }
public string Name { get; set; }
// Navigations
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }// this is my junction table
}
这是我的SchoolsSchoolTypes表:(这是中间表)
答案 0 :(得分:0)
我认为您在问题中的模型不完整。它缺少“加入”实体。
也就是说,如果您有一个“纯”连接实体,并且除了键(由外键组成)之外没有其他属性,则应将类型添加到“学校”类的“ SchoolsSchoolTypes”集合中。添加实体的代码应如下所示:
var schoolsObj = _GpsContext.School.Include(s => s.SchoolsSchoolTypes ).FirstOrDefault(x => x.ID == Guid.Parse(schoolUpdateVm.id)); //Include types to verify isn't already added
if (schoolsObj == null) throw new Exception("School not found");
if(schoolsObj.SchoolsSchoolTypes.Any(st=>st.SchoolTypeId == schoolUpdateVm.schoolTypeId) throw new Exception("School already has this type");
var schoolTypeObj = _GpsContext.SchoolsSchoolTypes.FirstOrDefault(x => x.SchoolTypeId == Guid.Parse(schoolUpdateVm.schoolTypeId));
if (schoolsObj == null) throw new Exception("School type not found");
schoolsObj.SchoolsSchoolTypes.Add(schoolTypeObj);
await _GpsContext.SaveChangesAsync();
如果“加入实体”具有其他属性(我怀疑是这种情况),那么您必须先创建新的加入实体,然后再将其添加到集合中:
var schoolsObj = _GpsContext.School.Include(s => s.SchoolsSchoolTypes ).FirstOrDefault(x => x.ID == Guid.Parse(schoolUpdateVm.id)); //Include types to verify isn't already added
if (schoolsObj == null) throw new Exception("School not found");
if(schoolsObj.SchoolsSchoolTypes.Any(st=>st.SchoolTypeId == schoolUpdateVm.schoolTypeId) throw new Exception("School already has this type");
var schoolTypeObj = _GpsContext.SchoolTypes.FirstOrDefault(x => x.SchoolTypeId == Guid.Parse(schoolUpdateVm.schoolTypeId));
if (schoolsObj == null) throw new Exception("School type not found");
var newSchollType = new SchoolsSchoolTypes()
{
SchollId = Guid.Parse(schoolUpdateVm.id),
SchoolTypeId = Guid.Parse(schoolUpdateVm.schoolTypeId),
OtherProperty = "OtherPropertyValue"
}
schoolsObj.SchoolsSchoolTypes.Add(newSchollType);
await _GpsContext.SaveChangesAsync();