I’m having troubles with creating and/or storing m:n relationship with EF 4.3 Code first
So the first entity Publication is defined as with some other internal scalar properties:
public class Publication : IDataErrorInfo{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PublicationId { get; set; }
[InverseProperty("Publications")]
public virtual ICollection<Group> Groups { get; set; }
and the other class in the same way:
public class Group : IDataErrorInfo {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GroupId { get; set; }
[InverseProperty("Groups")]
public ICollection<Publication> Publications { get; set; }
which according to numerous articles should be fine.
There are several problems I occur. AT first:
- If I create a new publication and assert it some Groups. All is stored to the db. But then I restart the program, the same particular publication has ICollection set to null. Therefore the information about relationship with Group has been deleted.I don’t know why 🙁
- When I try to update exisiting Publication entry with Group relationship, the DBUpdateException is thrown with the following text:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types
In the inner exception is the same, and in the inner exception of this one is the following:
Violation of PRIMARY KEY constraint ‘PK_Publicat_3AF5D6A10AD2A005′. Cannot insert duplicate key in object ‘dbo.PublicationGroups’.
The statement has been terminated.
I’m asserting the the new values of the Publication as follows:
var entry = db.Publications.First(a => a.PublicationId == publKey);
entry.Groups = db.Groups.
Where(a => groupKeys.Contains(a.GroupId)).
Select(b => b).
ToList();
where publKey is the key of the edited entity and groupKeys is the List of GroupId which should be the publication be related to.
after calling db.SaveContext() the exception is thrown
This topic has been covered by numerous articles, but I didn’t find any solution. All of the examples are using the same code, but apparently I’m missing something. I’m using SQL Ce 4.0 as the persistance data storage.
Thank you guys for answer, I’m dealing with it since yesterday, but don’t why this happens
Are you calling .Save after you’ve added the groups to the database? Otherwise when you try to add the groups to the publication, they won’t actually be in the DbSet yet. The following code works for me – perhaps you could clarify how it differs from yours?
(Code Updated to use SqlCe provider)