I have one to many relationship in my web forms project. And always get the same error: "an entity object cannot be referenced by multiple instances of ientitychangetracker" . How can I solve this problem, and how can I add items in one to many relationships by using entity framework? Here is example code:
MusicianManager mm = new MusicianManager();
Musician m = new Musician();
m.MusicianName = txtMusicianName.Text;
m.MusicianSurname = txtMusicianSurname.Text;
m.MusicianInstrument = txtInstrument.Value;
CountryManager cm = new CountryManager();
m.Country = cm.GetById(Convert.ToInt32(drpLstCountry.SelectedValue));
int id = mm.Add(m);
CountryManager class:
using ROCK.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ROCK.DataAccess
{
public class CountryManager
{
public Country GetById(int id)
{
RockolektifDatabaseEntities rde = new RockolektifDatabaseEntities();
return rde.Countries.FirstOrDefault(c => c.CountryId == id);
}
}
}
MusicianManager classs:
using ROCK.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ROCK.DataAccess
{
public class MusicianManager
{
public int Add(Musician m)
{
RockolektifDatabaseEntities rde = new RockolektifDatabaseEntities();
rde.Musicians.Add(m);
rde.SaveChanges();
List<Musician> m2 = rde.Musicians.OrderByDescending(mm => mm.MusicianId).Take(1).ToList();
foreach (var item in m2)
{
return item.MusicianId;
}
return -1;
}
}
}
I use Entire Design - (dataaccess, entity and userinterface.)