简体   繁体   中英

Entity Framework Code First relation in one table

I've a problem with creating a relation in one table. I have a UserProfile class. An another user can by only created by existing user. So I want to have fields with information about who created user and when the user was created. Maybe the code will say more :)

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    [Required, MaxLength(30)]
    public string UserName { get; set; }

    [Column(TypeName = "date")]
    [Display(Name = "Data ważności")]
    public DateTime ExpirationDate { get; set; }

    [DataType(DataType.DateTime)]
    [Display(Name = "Data dodania")]
    [Column(TypeName = "datetime")]
    public DateTime sysRegDate { get; set; }

    [ForeignKey("sysRegUser")]
    public int? sysRegUserId { get; set; }

    [DataType(DataType.DateTime)]
    [Column(TypeName = "datetime")]
    public DateTime sysModDate { get; set; }

    [ForeignKey("sysModUser")]
    public int? sysModUserId { get; set; }

    public virtual UserProfile sysRegUser { get; set; }
    public virtual UserProfile sysModUser { get; set; }
}

But when I'm creating a migration I get error:

System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'UserProfile_sysModUser_Source' in relationship 'UserProfile_sysModUser'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

Thanks in advance for answers.

I have used this code to create a parent-child relation, maybe it helps:

public class MyModel
{
  public int Id {get;set;}

  // ...

  public int? ParentId {get;set;}
  public virtual MyModel Parent {get;set;}

  public virtual IList<MyModel> Children {get;set;}
}

And in the DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<MyModel>().HasOptional(p => p.Parent).WithMany(p => p.Children).HasForeignKey(p => p.ParentId);
  modelBuilder.Entity<MyModel>().Property(p => p.ParentId).HasColumnName("Parent");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM