1
I need to map the Person and Branch classes with a one-to-one relationship, where a person will be just a branch and a branch will be tied to only one person, (A PK in Person Id and PK/FK in Affiliate Id). Entity Framework Core is getting confused and putting PK in Affiliate Id and FK in Person. I created a class called Entity that contains an Id property for everyone to inherit from. 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();
}
}
Try to do: Uilder.Hasone(u => u.Branch). Withone(p => p.Person). Hasforeignkey<Branch>(b => b.Filialid); in Person mapping
– Gabriel Coletta
It worked!!! Thank you Gabriel! :)
– Master JR
Ah! comments there on the question so I can define it as an answer.
– Master JR