In my project ,I used repository and used dependency injection (Autofac Mvc).
My IReposiroty =
public interface IRepository<T> where T:class
{
IEnumerable<T> GetAll();
T GetById(int id);
T Get(Expression<Func<T,bool>> expression);
IQueryable<T> GetMany(Expression<Func<T, bool>> expression);
bool Insert(T obj);
bool Update(T obj);
bool Delete(int id);
int Count();
bool Save();
}
My IPropertyOptionLangRepository
public interface IPropertyOptionLangRepository : IRepository<PropertyOptionLang>
{
}
My PropertyOptionRepository (Just Insert and Save Methods)
public bool Insert(PropertyOptionLang obj)
{
try
{
_database.PropertyOptionLang.Add(obj);
var num=_database.SaveChanges();
return true;
}
catch(Exception e)
{
Console.WriteLine(e);
return false;
}
}
public bool Save()
{
try
{
_database.SaveChanges();
return true;
}
catch
{
return false;
}
}
And My Controller ( constructor and Insert Method)
private readonly IPropertyOptionRepository _propertyOptionRepository ;
private readonly IPropertyOptionLangRepository _propertyOptionLangRepository ;
private readonly ILanguageRepository _languageRepository;
public FieldController(IPropertyOptionRepository propertyOptionRepository,
IPropertyOptionLangRepository propertyOptionLangRepository,
ILanguageRepository languageRepository)
{
_languageRepository = languageRepository;
_propertyOptionRepository = propertyOptionRepository;
_propertyOptionLangRepository = propertyOptionLangRepository;
}
public ActionResult Add()
{
PropertyOptionLang test3 = new PropertyOptionLang();
var option = _propertyOptionRepository.GetById(2);
var lang2 = _languageRepository.GetById(2);
test3.Language = lang2;
test3.PropertyOption = option;
test3.Name = "hasan";
test3.Prefix = "test2";
test3.Value = "aaa";
_propertyOptionLangRepository.Insert(test3);
_propertyOptionLangRepository.Save();
}
exception message is : " e.Message "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
thanks for help..
Note: I search already for this exception message but I failed again
Edit: For Autofac configurate I created a new class and update global.asax for startup. `public static class Bootstrapper {
public static void RunConfig()
{
BuildAutofac();
}
private static void BuildAutofac()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<LanguageRepository>().As<ILanguageRepository>();
builder.RegisterType<PropertyOptionLangRepository>().As<IPropertyOptionLangRepository>();
builder.RegisterType<PropertyOptionRepository>().As<IPropertyOptionRepository>();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}`