简体   繁体   中英

Entity Framework table relations

Introduction

  • I am new to Entity Framework
  • I am using Code-first

Use-case

I have to following tables

[Table("TBL_UserVariant")]
public class UserVariant
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }
    [Key, Column(Order = 1)]
    public int VarId { get; set; }
    public string Value { get; set; }
}

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

    public string eMail { get; set; }
}

I want TBL_UserProfile to refer a list of all TBL_UserVariant entries where TBL_UserProfile::UserId == TBL_UserVariant::UserId

The following is an example of my aim

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

    public string eMail { get; set; }

    public UserVariant[] variants;
}

Where 'UserProfile::variants' should include a list of items where 'TBL_UserProfile::UserId == TBL_UserVariant::UserId'

Question

Is this directly possible using EF ? OR, should I implement a wrapper populating 'UserProfile::variants' ~manually~ ?

You have to just add a navigation property to the UserProfile entity.

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

        public string eMail { get; set; }
        public virtual ICollection<UserVariant> UserVariants { get; set; }
    }

The following is what you should need. EF will take care of the rest.

[Table("TBL_UserProfile")]
public class UserProfile
{
    [Key]
    public int UserId { get; set; }
    public string eMail { get; set; }

    public virtual ICollection<UserVariant> Variants { get; set; }
}

[Table("TBL_UserVariant")]
public class UserVariant
{
    [Key]
    public int VarId { get; set; }
    public UserProfile User { get; set; }
    public string Value { get; set; }
}

I think what you're asking for is that you want to have one UserProfile , mapped to Many UserVariants

In that case you'll need to add a collection to your UserProfile class.

public virtual ICollection<UserVariant> UserVariants { get; set; }

You'll also need to fix the [Key] property on the UserVariant class as I believe it should be on VarId. You can then just specify a navigation property

[Key]
public int VarId { get; set; }
public UserProfile User { get; set; }

Edit

As an aside, your naming conventions are all over the place. Don't prefix your table names with TBL_ . Capitalise all your properties/Columns. eg Email not eMail

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