Code First Relationship Migration and Insert?

Asked

Viewed 292 times

1

I’m using UserManager to manage users, I am using migration and I’m having relationship trouble.

I happen to have the entity Cliente:

public class Cliente : IdentityUser
{
    [NotMapped]
    public string Senha { get; set; }

    [Required]
    public string NomeCompleto { get; set; }


    public virtual ICollection<Pedido> Pedidos { get; set; }

    // Telefone
    [Required]
    public virtual TelefoneCliente Telefone { get; set; }

    // Documento
    [Required]
    public virtual DocumentoCliente Documento { get; set; }

    // Endereço
    [Required]

    public virtual EnderecoCliente Endereco { get; set; }
}

Which has 1=1 relationship with Addressee:

public class EnderecoCliente
{
    [Key, ForeignKey("Id")]
    public virtual Cliente Cliente { get; set; }

    public string Id { get; set; }
    [Required]
    public Estado Estado { get; set; }
    [Required]
    public Cidade Cidade { get; set; }
    [Required]
    public string CEP { get; set; }
    [Required]
    public string Bairro { get; set; }
    [Required]
    public string Rua { get; set; }
    [Required]
    public string Numero { get; set; }

    public string Complemento { get; set; }
}

And the Addressecustomer has relationship with State and City that are fixed data in the table.

When I send the model with this structure the model and its relationships are ok, but it tries to include and make an Index in the City and State table and obviously generates error because this record already exists, what needs to be done is just add the id reference in the Addressee table.

Code to enter client

var result = await UserManager.CreateAsync(model, model.Senha);

State:

public class Estado
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string NomeEstado { get; set; }
}

City:

public class Cidade
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string NomeCidade { get; set; }

    public Estado Estado { get; set; }
}

Someone can help me??

@@Edit

Follow me Dbcontext

public class EfDbContext : IdentityDbContext<Cliente>
{
    public EfDbContext() : base ("EFDbContext")
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Produto> Produtos { get; set; }
    public DbSet<Administrador> Administradores { get; set; }
    public DbSet<Cliente> Cliente { get; set; }

    public static EfDbContext Create()
    {
        return new EfDbContext();
    }

    public DbSet<Categoria> Categorias { get; set; }
    public DbSet<MarcaVitrine> MarcaVitrine { get; set; }
    public DbSet<ClubesNacionais> ClubesNacionais { get; set; }
    public DbSet<ClubesInternacionais> ClubesInternacionais { get; set; }
    public DbSet<FaixaEtaria> FaixasEtarias { get; set; }
    public DbSet<Genero> Generos { get; set; }
    public DbSet<Grupo> Grupos { get; set; }
    public DbSet<Marca> Marcas { get; set; }
    public DbSet<Modalidade> Modalidades { get; set; }
    public DbSet<SubGrupo> SubGrupos { get; set; }
    public DbSet<ProdutoVitrine> ProdutoVitrine { get; set; }
    public DbSet<QuironProduto> QuironProdutos { get; set; }
    public DbSet<Cor> Cores { get; set; }
    public DbSet<Tamanho> Tamanhos { get; set; }
    public DbSet<Estoque> Estoque { get; set; }
    public DbSet<ProdutoModelo> ProdutoModelo { get; set; }
    public DbSet<Cidade> Cidade { get; set; }
    public DbSet<Estado> Estado { get; set; }
    public DbSet<Pedido> Pedidos { get; set; }
    public DbSet<ProdutoPedido> ProdutosPedidos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Produto>().ToTable("Produtos");
        modelBuilder.Entity<Administrador>().ToTable("Administradores");

        base.OnModelCreating(modelBuilder);
    }

}

1 answer

0

I believe the problem is because city and state entities are detached from their context, try to do the following before calling the UserManager.CreateAsync(model, model.Senha):

if (UserManager.Entry(model.Cidade).State == EntityState.Detached)
    UserManager.Cidades.Atach(model.Cidade);

if (UserManager.Entry(model.Estado).State == EntityState.Detached)
    UserManager.Estados.Atach(model.Estado);

I don’t know if this will solve your problem, because I don’t know the code you are using in your Dbcontext (Usermanager).

  • Thanks for answering, there is no Entry option and I also do not see the entity in Usermanager, nor references to be added to work.

  • Usermanager is not Dbcontext but Usermanager from Asp.net.Identity so it does not have these options

Browser other questions tagged

You are not signed in. Login or sign up in order to post.