Many-to-many relationship - ArgumentNullException: Value cannot be null. (Parameter 'name')
See original GitHub issueDescribe the bug
ArgumentNullException
is thrown when entities have a many-to-many relationship.
To Reproduce Here is a repository with a ready-to-run project that demonstrates the issue: AuditExample
We have two entities: Person
and Department
that have a many-to-many relationship via two navigation properties Person.Departments
and Department.Persons
:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Department> Departments { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
The relationship is explicitely configured the following:
public class PersonsContext : AuditDbContext
{
// ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasMany<Department>(x => x.Departments).WithMany(x => x.Persons);
}
}
However, omitting the fluent configuration doesn’t change the behavior. But deriving from DbContext
instead of AuditDbContext
fixes the problem.
Here is the part of the main method with the issue:
// ...
context.Departments.Add(new Department() { Id = 1, Name = "Development" });
context.Departments.Add(new Department() { Id = 2, Name = "Research" });
context.SaveChanges();
context.Persons.Add(new Person() { Id = 1, Name = "Alice", Departments = context.Departments.ToList() });
context.Persons.Add(new Person() { Id = 2, Name = "Bob", Departments = context.Departments.ToList() });
// ArgumentNullException will be thrown here: Value cannot be null. (Parameter 'name')
context.SaveChanges();
Expected behavior No exception should be thrown and the audit information should be written.
Libraries (specify the Audit.NET extensions being used including version):
- Audit.EntityFramework.Core: 16.4.0
Target .NET framework:
- .NET 5.0
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (2 by maintainers)
Top GitHub Comments
First of all I want to thank you for your cooperation sharing a project that reproduces the issue, I wish all the issues were described as you did…
The problem was because of EF Core changes on the latest version that, as usually, affects the libraries that depends on the representation of the EF ChangeTracker.
Anyway I’ve fixed the issue on version 16.4.1, please upgrade your references and re-test.
Thank you for your quick response. No worries about the demo project, it should anyway be the standard in my opinion.
Thanks a lot. The new version works like a charm.