none
Code First - Many to Many with Repository RRS feed

  • Question

  • Hi

    I have the entities

    public class Usuario
    {
    
    	public Usuario()
    	{
    		this.Empresas = new List<Empresa>();
    	}
    
    	public int UsuarioId { get; set; }
    
    	public string Legajo { get; set; }
    	public string Password { get; set; }
    	public string Nombre { get; set; }
    	public string Apellido { get; set; }
    
    	public virtual Empresa EmpresaDefault { get; set; }
    
    	public virtual ICollection<Empresa> Empresas { get; set; }
    
    }
    
    public class Empresa
    {
    	public int EmpresaId { get; set; }
    	public string NombreEmpresa { get; set; }
    
    	public virtual ICollection<Usuario> Usuarios { get; set; }
    
    }

    and the mapping

    class UsuarioMapping : EntityTypeConfiguration<Usuario>
    {
    	public UsuarioMapping()
    	{
    		HasKey(x => x.UsuarioId);
    		Property(x => x.UsuarioId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    
    		HasMany<Empresa>(x => x.Empresas)
    					.WithMany(x => x.Usuarios)
    					.Map(x =>
    					{
    						x.MapLeftKey("UsuarioId");
    						x.MapRightKey("EmpresaId");
    						x.ToTable("Usuario_Empresa");
    					});
    
    
    		HasRequired(x => x.EmpresaDefault).WithMany().Map(x => x.MapKey("EmpresaDefault"));
    	}
    
    }


    I can analize several implementation, but all use directly the context to add entities and relation, the problem is how can I implement used respository?

    the entities are desattached from context when I create the entity and relation

    The generics repository class is implemented

    public abstract class RepositoryBase<T> : IRepository<T> where T : class
    {
    
    	//others repository methods
    
    	public virtual void Update(T entity, List<string> unchangeProp = null)
    	{
    		using (NovedadesCapatazContext context = new NovedadesCapatazContext())
    		{
    			context.Entry<T>(entity).State = EntityState.Modified;
    
    			if (unchangeProp != null)
    			{
    				foreach (string property in unchangeProp)
    				{
    					PropertyInfo propertyInfo = typeof(T).GetProperty(property);
    					var value = propertyInfo.GetValue(entity, null);
    
    				   
    					if (propertyInfo.PropertyType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(propertyInfo.PropertyType.GetGenericTypeDefinition()))
    					{
    						ICollection item = (ICollection)value;
    						if (item != null)
    						{
    							foreach (object o in item)
    							{
    								context.Entry(o).State = EntityState.Modified;
    							}
    						}
    					}
    					else
    						context.Entry(value).State = EntityState.Unchanged;
    				}
    			}
    
    			context.SaveChanges();
    		}
    	}
    
    }

    I can attach into the context the principal entity, and detect by reflection de "Empresa" collection, but if I use

    context.Entry(o).State = EntityState.Modified;

    or EntityState.Unchanged

    the changes aren't reflect in the database, EF never delete existing relation and create the new

    the EntityState.Added cause an exception

    Cannot insert the value NULL into column 'EmpresaId', table 'Empresas'; column does not allow nulls. INSERT fails.

    How can I implement many to many used repository?

    greetings


    Leandro Tuttini

    Blog
    Buenos Aires
    Argentina

    Saturday, June 22, 2013 3:09 PM

Answers