The following is the data in the database
{
"Description": "Factory1",
"Areas": [
{
"Description": "area1",
"Name": "area1",
"Id": 1
},
{
"Description": "area2",
"Name": "area2",
"Id": 2
}
],
"Name": "Factory1",
"Id": 1
}
The following is the incoming data
{
"Description": "Factory1",
"Areas": [
{
"Description": "area1",
"Name": "area1",
"Id": 1
}
],
"Name": "Factory1",
"Id": 1
}
This will not remove area2 from Factory1, but changes to area1 and Factory1 will take effect.I have tried adding new areas and editing existing areas, and both are working properly, but deleting an area relationship does not work.Does EF not support this operation?
Following is my code
public BaseOutput UpdateObject(string ClassName, JsonElement obj)
{
BaseOutput output = new BaseOutput();
Type targetType = Type.GetType($"MCS.Object.{ClassName},MCS.Object");
var v = JsonSerializer.Deserialize(obj, targetType);
string methodName = MethodBase.GetCurrentMethod().Name;
MethodInfo method = this.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(targetType); ;
output.Result = method.Invoke(this, new object[] { v });
return output;
}
private TEntity UpdateObject<TEntity>(TEntity Entity)
where TEntity : CommonEntity<TEntity>, new()
{
using (var repository = Db.GetSqlRepository())
{
repository.Context.Update(Entity);
repository.Context.SaveChanges();
return Entity;
}
}
public class Factory : CommonEntity<Factory>, IEntityTypeBuilder<Factory>
{
public string? Description { get; set; }
public UniversalType Type { get; set; }
public List<Area> Areas { get; set; }
public new void Configure(EntityTypeBuilder<Factory> entityBuilder, DbContext dbContext, System.Type dbContextLocator)
{
base.Configure(entityBuilder, dbContext, dbContextLocator);
//entityBuilder.HasMany(x => x.Areas).WithOne(x => x.Factory);
entityBuilder.Navigation(x => x.Areas).AutoInclude();
//entityBuilder.HasOne(x => x.Type);
entityBuilder.Navigation(x => x.Type).AutoInclude();
}
}
public class Area : CommonEntity<Area>, IEntityTypeBuilder<Area>
{
public string? Description { get; set; }
public Factory? Factory { get; set; }
public UniversalType Type { get; set; }
public new void Configure(EntityTypeBuilder<Area> entityBuilder, DbContext dbContext, Type dbContextLocator)
{
base.Configure(entityBuilder, dbContext, dbContextLocator);
entityBuilder.Navigation(x => x.Factory).AutoInclude();
}
}
When an existing area is passed in, it will be automatically created.