Hi I want create one to one relation ship with entity .net framework in C# windows form. but i get this error:
System.Data.Entity.ModelConfiguration.ModelValidationException: 'One or more validation errors were detected during model generation:
person_pos_Source: : Multiplicity is not valid in Role 'person_pos_Source' in relationship 'person_pos'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. '
this is my code for person and their position table:
public class pos
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid id { get; set; }
[Required, Column(TypeName = "nvarchar")]
[MaxLength(50)]
public string name { get; set; }
public virtual person person { get; set; }
}
public class person
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid id { get; set; }
[Required, Column(TypeName = "nvarchar")]
[MaxLength(50)]
public string name { get; set; }
[Required, Column(TypeName = "nvarchar")]
[MaxLength(50)]
public string family { get; set; }
public int? age { get; set; }
public DateTime Createdata { get; set; }
[ForeignKey("pos")]
public Guid posId { get; set; }
public virtual pos pos { get; set; }
}
how can I fix this?
CodePudding user response:
I would use fluent API for that (you need to override OnModelCreating
method of DbContext
):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<pos>()
.HasOne<person>(x => x.pos)
.WithOne(x => x.person)
.HasForeignKey<person>(ad => ad.posId);
}
CodePudding user response:
A few things are fundamentally wrong here.
A 1:1 relationship can be achieved by having the primary of another table as the foreign key and also for the other referred table (non-nullable).
So you should have your relationship like this.
public class Class1
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id {get;set;}
[Required]
public virtual Class2 Class2 {get;set;}
}
public class Class2
{
[Key, ForeignKey("Class1")]
public int Id {get;set;}
[Required]
public virtual Class1 Class1 {get;set;}
}