实体框架产生两个额外的列

时间:2015-07-28 05:10:10

标签: c# sql entity-framework entity-framework-6

我正在使用Entity Framework 6.X和代码优先方法。

我的要求是我有桌子

  1. 用户
  2. 产品
  3. 在输入产品时,我需要创建者名称,修改名称以跟踪,这两个应该引用用户表。因为输入/修改的人应该在用户表中。

    我的模特是:

    public class User : AuditableEntity
    {
        [Key]
        [StringLength(35)]
        public string UserId { get; set; }
    
        [Required]
        [Column(TypeName = "varchar")]
        public string Name { get; set; }
    
        public string Address { get; set; }
    
        [Required]
        public long MobileNo { get; set; }
    
        [Required]
        public string Password { get; set; }
    
        public string EmailId { get; set; }
    
        public string MiscData { get; set; }
    
        [Required]
        public Role Role { get; set; }
    
        public virtual ICollection<Product> Products { get; set; }
        public virtual ICollection<Product> Products1 { get; set; }
    }
    
    public class Product : AuditableEntity
    {
        [Key]
        [StringLength(30)]
        public string Id { get; set; }
    
        [Required]
        public string ProductName { get; set; }
    
        public string Description { get; set; }
    
        [Required]
        [Column(TypeName = "Money")]
        public decimal Amount { get; set; }
    
        [Required]
        [StringLength(35)]
        public override string CreatedBy
        {
            get
            {
                return base.CreatedBy;
            }
            set
            {
                base.CreatedBy = value;
            }
        }
    
        [Required]
        [StringLength(35)]
        public override string ModifiedBy
        {
            get
            {
                return base.ModifiedBy;
            }
            set
            {
                base.ModifiedBy = value;
            }
        }
    
        [ForeignKey("CreatedBy")]
        public User User { get; set; }
    
        [ForeignKey("ModifiedBy")]
        public User User1 { get; set; }
    }
    

    但是在执行此操作时,它会生成Db而不会出现错误,并在CreatedBy中的ModifiedByProduct列上创建外来列。但是,在产品中,它会创建User_UserIdUser_UserId1作为额外列。

    我是Entity Framework的新手。

    请帮帮我。

    更新

      

    当我将引用更改为一列时,只说CreatedBy表示额外列不在产品中。但是当我如上所示引用另一个列时,问题就会出现。

1 个答案:

答案 0 :(得分:2)

这并没有解决问题,只留下历史信息。请参阅最新解决方案。

this SO question。尝试像这样添加[InverseProperty("UserId ")]

[InverseProperty("UserId ")]
[ForeignKey("CreatedBy")]
public User User { get; set; }

[InverseProperty("UserId ")]
[ForeignKey("ModifiedBy")]
public User User1 { get; set; }

<强> UDPATE

此外,EF可能会混淆在哪里映射您的User.ProductsUser.Products1。有关代码优先关系的信息,请参阅this SO questionthis MSDN article。尝试将其更改为:

[InverseProperty("User")]
public virtual ICollection<Product> Products { get; set; }

[InverseProperty("User1")]
public virtual ICollection<Product> Products1 { get; set; }