【问题标题】:Entity Framework producing two extra columns实体框架产生两个额外的列
【发布时间】:2015-07-28 05:10:09
【问题描述】:

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

我的要求是我有桌子

  1. 用户
  2. 产品

在输入产品时,我需要创建者名称、修改器名称来跟踪,这两个应该引用用户表。因为那些输入/修改的人应该在一个用户表中。

我的模型是:

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 而不会出错,并在 ProductCreatedByModifiedBy 列上创建外部列。但是在产品中,它会创建 User_UserIdUser_UserId1 作为额外的列。

我是实体框架的新手。

请帮帮我。

更新

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

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • 我试过像你说的那样给我这个错误属性必须是有效的实体类型,并且属性应该有一个非抽象的 getter 和 setter
  • 谢谢你真的节省了我的时间。因为我很新,所以我没能得到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多