Reputation: 78
I'm using Entity Framework Core 1 ou "7.0.0-rc1-final". I trying to do a entity self reference but it isn't work. Follow the exemplo:
public class Unidade
{
[Key]
public Int32 IdUnidade { get; set; }
public Int32? IdUnidadePai { get; set; }
public String Nome { get; set; }
public ICollection<Unidade> LstFilhos { get; set; }
public Unidade UnidadePai { get; set; }
}
Follow the mapping:
public UnidadeConfiguration(EntityTypeBuilder<Unidade> paramModelBuilder)
{
paramModelBuilder.HasKey(x => x.IdUnidade);
paramModelBuilder.HasMany(x => x.LstFilhos)
.WithOne(x => x.UnidadePai)
.HasForeignKey(c => c.IdUnidadePai);
paramModelBuilder.ToTable("Unidade","Unidade");
}
I have already try this to:
paramModelBuilder.HasOne(x => x.UnidadePai)
.WithMany(x => x.LstFilhos)
.HasForeignKey(x => x.IdUnidade);
And try this to:
paramModelBuilder.HasMany(x => x.LstFilhos)
.WithOne(x => x.UnidadePai)
.HasForeignKey("IdUnidade", "IdUnidadePai");
My Database sql:
CREATE TABLE [Unidade].[Unidade](
[IdUnidade] [int] IDENTITY(1,1) NOT NULL,
[IdUnidadePai] [int] NULL,
[Nome] [varchar](100) NOT NULL,
CONSTRAINT [PK_Unidade] PRIMARY KEY CLUSTERED
(
[IdUnidade] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [Unidade].[Unidade] WITH CHECK ADD CONSTRAINT [FK_Unidade_Unidade]
FOREIGN KEY([IdUnidadePai])
REFERENCES [Unidade].[Unidade] ([IdUnidade])
GO
ALTER TABLE [Unidade].[Unidade] CHECK CONSTRAINT [FK_Unidade_Unidade]
GO
So, when I try to get one element the element, I have some scenarios:
I really don't know what I do.
Upvotes: 0
Views: 1439
Reputation: 155
I've tried to generate code first classes for the database table, you'have posted. So, that's the result:
public partial class Unidade
{
public int IdUnidade { get; set; }
public int? IdUnidadePai { get; set; }
public string Nome { get; set; }
public virtual Unidade IdUnidadePaiNavigation { get; set; }
public virtual ICollection<Unidade> InverseIdUnidadePaiNavigation { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Unidade>(entity =>
{
entity.HasKey(e => e.IdUnidade);
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar");
entity.HasOne(d => d.IdUnidadePaiNavigation).WithMany(p => p.InverseIdUnidadePaiNavigation).HasForeignKey(d => d.IdUnidadePai);
});
}
If you wanna try to self generate these, I've used the following command:
dnx ef dbcontext scaffold "Data Source=.;Initial Catalog=Unidade;Integrated Security=True;MultipleActiveResultSets=True" EntityFramework.MicrosoftSqlServer
Of course, you have to change the connection string name according to your db settings. You can read detailed explanation of what should you do here: Entity Framework 7 DbContext scaffold
Upvotes: 1