Reputation: 93
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!
Upvotes: 0
Views: 36
Reputation: 1054
Change:
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;}
}
To:
public class Application
{
private List<Developer> _Developers;
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Note { get; set; }
[Required(ErrorMessage="The Id Of Owner(owner as a developer) is Required")]
public int DeveloperId { get; set; }
[ForeignKey("DeveloperId")]
public virtual Developer Owner { get; set;}
public virtual List<Developer> Developers { get{return _Developers;}} // This create Many to many
public application(){
_Developers= new List<Developer>();
}
}
Upvotes: 1