Update relationships when saving changes of EF4 POCO objects

后端 未结 5 2280
野趣味
野趣味 2020-11-21 22:33

Entity Framework 4, POCO objects and ASP.Net MVC2. I have a many to many relationship, lets say between BlogPost and Tag entities. This means that in my T4 generated POCO Bl

5条回答
  •  佛祖请我去吃肉
    2020-11-21 23:13

    All of the answers were great to explain the problem, but none of them really solved the problem for me.

    I found that if I didn't use the relationship in the parent entity but just added and removed the child entities everything worked just fine.

    Sorry for the VB but that is what the project I am working in is written in.

    The parent entity "Report" has a one to many relationship to "ReportRole" and has the property "ReportRoles". The new roles are passed in by a comma separated string from an Ajax call.

    The first line will remove all the child entities, and if I used "report.ReportRoles.Remove(f)" instead of the "db.ReportRoles.Remove(f)" I would get the error.

    report.ReportRoles.ToList.ForEach(Function(f) db.ReportRoles.Remove(f))
    Dim newRoles = If(String.IsNullOrEmpty(model.RolesString), New String() {}, model.RolesString.Split(","))
    newRoles.ToList.ForEach(Function(f) db.ReportRoles.Add(New ReportRole With {.ReportId = report.Id, .AspNetRoleId = f}))
    

提交回复
热议问题