【问题标题】:How do i map a column to another table in entity framework?如何将列映射到实体框架中的另一个表?
【发布时间】:2014-08-09 17:12:15
【问题描述】:

假设我有两个班级,

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

我的问题是,如何将 UserPosts 中的 CreatedBy 映射到 UserBio 中的 Id 属性?我知道一种方法是用 UserBio 替换 CreatedBy 的数据类型。但由于某些问题,这似乎不是一个好主意。我想将 CreatedBy 作为字符串插入,在检索期间,UserPosts 还包含用户的 UserBio。 你能帮我解决这个问题吗?我必须为此使用 Fluent api 吗?或者我可以通过数据注释来实现吗?

【问题讨论】:

  • 下面的回答是否帮助或回答了您的问题?

标签: c# asp.net asp.net-mvc entity-framework entity-framework-6


【解决方案1】:

我正在使用设计器从数据库创建我的类,但我相信这将适用于您的情况。我认为您需要做的是在 UserPosts 类型的 UserBio 类中创建一个公共虚拟属性。

 public virtual UserBio users { get; set; }

访问 UserPost 时,您可以引用创建该帖子的用户。然后我将摆脱 createdBy 属性,因为不再需要它。

【讨论】:

    【解决方案2】:
     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; }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 2013-02-18
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 2011-01-04
      相关资源
      最近更新 更多