I need to map the Person and Branch classes with one-to-one relationship, where a person will be just a branch and a branch will be linked to only one person, (A PK in Person ID and PK / FK in Branch ID). The Entity Framework Core is getting confused and putting PK in the Branch ID and FK in Person. I created a class called Entity that contains an Id property for all to inherit from it. I think this is causing the problem.
public abstract class Entity
{
public Guid Id { get; protected set; }
public override bool Equals(object obj)
{
var compareTo = obj as Entity;
if (ReferenceEquals(this, compareTo)) return true;
if (ReferenceEquals(null, compareTo)) return false;
return Id.Equals(compareTo.Id);
}
public static bool operator ==(Entity a, Entity b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
return true;
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;
return a.Equals(b);
}
public static bool operator !=(Entity a, Entity b)
{
return !(a == b);
}
public override int GetHashCode()
{
return (GetType().GetHashCode() * 907) + Id.GetHashCode();
}
public override string ToString()
{
return GetType().Name + " [Id=" + Id + "]";
}
}
public class Pessoa : Entity
{
public virtual Filial Filial { get; private set; }
protected Pessoa() { }
public Pessoa( Guid id, PessoaNatureza pessoaNatureza)
{
Id = id;
PessoaNatureza = pessoaNatureza;
}
}
public class Filial : Entity {
public virtual Pessoa Pessoa { get; set; }
protected Filial() { }
public Filial(Guid id)
{
Id = id;
}
}
// Mappings
public class FilialMap : IEntityTypeConfiguration<Filial>
{
public void Configure(EntityTypeBuilder<Filial> builder)
{
builder.ToTable("tblFilial");
builder.HasKey(f => f.Id);
builder
.HasOne(u => u.Pessoa)
.WithOne(p => p.Filial)
.HasConstraintName("FK_Pessoa_Filial")
.IsRequired();
builder.Property(f => f.Id)
.ValueGeneratedNever()
.HasColumnName("PessoaId")
.IsRequired();
}
}
public class PessoaMap : IEntityTypeConfiguration<Pessoa>
{
public void Configure(EntityTypeBuilder<Pessoa> builder)
{
builder.ToTable("tblPessoa");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id)
.HasColumnName("PessoaId")
.IsRequired()
.ValueGeneratedNever();
builder.Property(p => p.PessoaNatureza)
.HasColumnName("PessoaNaturezaId")
.IsRequired();
}
}