JonPSmith / GenericServices

GenericServices helps with building a service/application layer in a .NET based application using EF6.x
MIT License
247 stars 44 forks source link

eror while using updateservice on dto that has list of dto inside #22

Closed BatelAyala closed 3 years ago

BatelAyala commented 3 years ago

I using the detailsservice to get my dto object and then I try to update with the result and I get error on savechanges(): 'The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted

I am using the following code: var service = new DetailService<aClass, aClassDTO>(ctx); var query = service.GetDetailUsingWhere(i => i.UserID == userId); result = query.Result; var service1 = new UpdateService<aClass, aClassDTO>(ctx); service1.Update(result);

my class define like this:

public class aClassDTO: EfGenericDto<aClass, aClassDTO>
 {
    public aClassDTO()
    {
        bClassList = new List<bClassDTO>();
    }
    [Key]
    public int Id { get; set; }

    public string PropertyA {get;set;}

    public int PropertyB {get;set;}

    public List<bClassDTO> bClassList { get; set; }

    protected override Type AssociatedDtoMapping
    {
        get { return typeof(bClassDTO); }
    }
    protected override CrudFunctions SupportedFunctions
    {
        get { return CrudFunctions.AllCrud; }
    }
}

public class bClassDTO: EfGenericDto<bClass, bClassDTO>
{

    public int Id { get; set; }

    public int PropA { get; set; }

    public int PropB { get; set; }

    protected override CrudFunctions SupportedFunctions
    {
        get { return CrudFunctions.AllCrud; }
    }

}

the dto classes are similar to the entities of the ef

can somebody help me understand what the problem is?

(it work fine when I tried to save aClassDTO without list-the problem occured only when the list have items-only in update on the first create it worked fine. I tried to see if the dto class on the list have problem so I tried to save it using a loop-it works fine but in the parent object save it failed)

JonPSmith commented 3 years ago

Hi @BatelAyala ,

Your code example isn't complete and I'm not sure what you are trying to do - are you trying to update the aClass and its bClasses - if so I don't see you setting up any bClasses.

Updating a class with relationships is difficult, so you might want to do this using the normal EF6 commands. I you want to try to make GenericServices work, then here are some useful links

  1. The document page on Update, especially at the end of the page.
  2. Link to article about create and update using GenericServices