I am new to EF and I am trying to work with a many-to-many relationship.
I have a Developers table and I have a Applications table.
Each developer can have many applications, and each application can have many developers.
I have tried to follow examples on StackOverflow where it mentions to attach, but I've tried everything and it still creates duplicate developers for an application.
public class Developer
{
public int DeveloperId { get; set; }
[Required]
public string DeveloperName { get; set; }
public virtual List<Application> Applications { get; set; }
}
public class Application
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Note { get; set; }
public Developer Owner { get; set;}
public virtual List<Developer> Developers { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Developer>()
.HasMany<Application>(d => d.Applications)
.WithMany(a => a.Developers)
.Map(ad =>
{
ad.MapLeftKey("DeveloperRefId");
ad.MapRightKey("ApplicationRefId");
ad.ToTable("DeveloperApplication");
});
}
Above describes my setup. I've tried so many things, but any time a new application is added, EF creates a new developer to associate with it.
context.Applications.Add(app);
// no matter what I try here I get a duplicate developer
context.SaveChanges();
return Ok(app.Id);
Any suggestions would be greatly appreciated! Thank you!
Application.Developerscollection? And what's the purpose ofApplication.Ownerproperty, which defines another one-to-many relationship betweenDeveloperandApplication? Your issue might be related to that property rather than the may-to-many relationship.