Irshu
Irshu

Reputation: 8436

How do i map a column to another table in entity framework?

Lets say i have two classes,

public class UserBio {
        [Key]
        public string Id { get; set; }
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
      }





 public class UserPosts
        {
            [Key]
            public int PostId { get; set; }
            public string CreatedBy { get; set; }
            public string Description { get; set; }
        }

my question is, how do i map the CreatedBy from UserPosts to the Id property in UserBio? I know one way is to replace the Datatype of CreatedBy with UserBio. But due to certain issues, it seems not a good idea. I want to insert the CreatedBy as string and during retrieval, the UserPosts also contains the UserBio of the user. Could you pls help me with this? Do i have to use the Fluent api for this? Or can i achieve with the data annotations?

Upvotes: 2

Views: 2402

Answers (2)

physics90
physics90

Reputation: 959

I am using the Designer to create my classes from a database, but I believe this will work for your situation. What I believe you need to do is to create a public virtual property in your UserPosts class of type UserBio.

 public virtual UserBio users { get; set; }

when accessing the UserPost you can then reference the users who created the post. I would then get rid of the createdBy property as that will not be needed any longer.

Upvotes: 1

Darshan P
Darshan P

Reputation: 2241

 public class UserPosts
 {
     [Key]
     public int PostId { get; set; }

     [ForeignKey("User")]
     public string CreatedBy { get; set; }
     public virtual UserBio User { get; set; }

     public string Description { get; set; }
 }

Upvotes: 0

Related Questions