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

asp.net asp.net-mvc c# entity-framework entity-framework-6

Question

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?

1
2
8/9/2014 5:12:15 PM

Accepted Answer

 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; }
 }
0
8/9/2014 5:51:43 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow