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

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

Question

If I had two classes, for example

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; }
        }

How do I translate the CreatedBy from UserPosts to the Id attribute in UserBio? is my query. I am aware of one method, which is to substitute UserBio for the CreatedBy Datatype. But it doesn't seem like a good idea because of a few problems. The UserPosts also contain the user's UserBio during retrieval, and I want to insert the CreatedBy as a string. Please, could you assist me with this? Is the Fluent api required for this? Or what can I accomplish using 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

Although I am creating my classes from a database using the Designer, I think this will also work for you. What you should do, in my opinion, is add a public virtual property of type UserBio to your UserPosts class.

 public virtual UserBio users { get; set; }

The users who created the post can then be referred to when visiting the UserPost. The createdBy property would subsequently be removed because it was no longer required.



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