Using navigation properties in a LINQ query causes problems such as multiplicity of relationships

When I execute a request like:

    .Where(u => u.Id == _userContext.User.Id)
    .SelectMany(u => u.Houses)
    ... // more query stuff here


I do not have problems.

But when I do this:

    .Where(u => u.Id == _userContext.User.Id)
    ... // more query stuff here


errors such as

A multiplicity constraint violation has occurred: An EntityReference can have at most one related entity, but the request returned more than one related entity.

related to things in // more request stuff i think. Can someone please explain what is the difference between the two and why one might cause problems?


source to share

1 answer

I'm not 100% sure, but I have an idea of ​​what the problem is. Most likely it has more to do with the mappings of your objects (I assume this is an EF project). If you try to access the .Houses property in your first request, you will probably get the same error. Only the first one does not actually load Homes (this can be verified by running a SQL trace and seeing the SQL that is called in every query).

I assume you have some code somewhere, something like this?

        .HasRequired(t => t.Houses)
        .Map(c => c.MapKey("HouseId"));


If that's correct, you need to change your .WithOptional () to .WithMany (). This mapping is not prepared for the one-to-many relationship that appears to be happening here. If it isn't, could you at least post your model mappings, and maybe the generated SQL will be nice too.



All Articles