Reputation: 159
I have a problem in EF, it is duplicating column like 'MenuPai_Id' and 'MenuPai_Id1', here are the classes.
public class Menu :EntidadePadrao
{
public int? MenuPai_Id { get; set; }
public virtual Menu MenuPai { get; set; }
public virtual ICollection<Menu> MenusFilhos { get; set; }
public virtual ICollection<PerfilUsuarioMenu> PerfisUsuario { get; set; }
}
public class MenuMap : EntityTypeConfiguration<Menu>
{
public MenuMap()
{
// Primary Key
this.HasKey(t => t.Id);
this.ToTable("Menu");
this.Property(t => t.MenuPai_Id).HasColumnName("MenuPai_Id");
this.HasOptional(t => t.MenuPai)
.WithMany(t => t.MenusFilhos)
.HasForeignKey(d => d.MenuPai_Id);
}
}
And this is the sql generated for the table.
CREATE TABLE [dbo].[Menus] (
[Id] [int] NOT NULL IDENTITY,
[Sequencia] [int] NOT NULL,
[MenuPai_Id] [int],
[MenuPai_Id1] [int],
CONSTRAINT [PK_dbo.Menus] PRIMARY KEY ([Id]))
ALTER TABLE [dbo].[Menus] ADD CONSTRAINT [FK_dbo.Menus_dbo.Menus_MenuPai_Id1]
FOREIGN KEY ([MenuPai_Id1]) REFERENCES [dbo].[Menus] ([Id])
I have other mappings like this in the project, that was generated automatically and it's working fine. Just this class I added manually and I can't find why doesn't work at the same way.
I appreciate any help.
Edited: I just forgot this:
modelBuilder.Configurations.Add(new MenuMap());
Upvotes: 1
Views: 73
Reputation: 263683
MenuId
shouldn't be nullable since it is a primary key,
public class Menu :EntidadePadrao
{
public int MenuId { get; set; }
public int MenuPai_ID {get; set; }
// Navigation List
public Menu MenuPai { get; set; }
public virtual ICollection<Menu> MenusFilhos { get; set; }
public virtual ICollection<PerfilUsuarioMenu> PerfisUsuario { get; set; }
}
then in your configuration, tell EF that MenuPai_ID
is nullable.
public MenuMap()
{
// Primary Key
this.HasKey(t => t.MenuId);
// Property and Mapping
this.ToTable("Menu");
this.Property(t => t.MenuPai_ID)
.IsOptional()
.HasColumnName("MenuPai_ID");
// Relationship
this.HasOptional(t => t.MenuPai)
.WithMany(t => t.MenusFilhos)
.HasForeignKey(d => d.MenuPai_Id);
}
Upvotes: 1