实体框架无效的列名称,EF将数字1添加到主键

Jua*_*mez 8 entity-framework entity-framework-4 entity-framework-5

我有这两个实体

public partial class Suscriptores
{
    public Suscriptores()
    {
       this.Publicacion = new HashSet<Publicacion>();
    }

    [Key]
    public int IdSuscriptor { get; set; }
    public string LogoSuscriptor { get; set; }
    public string Identificacion { get; set; }
    public string Nombre { get; set; }
    public string Direccion { get; set; }
    public string Telefono { get; set; }
    public string Email { get; set; }
    public string Fax { get; set; }
    public string Home { get; set; }

    public virtual ICollection<Publicacion> Publicacion { get; set; }
}

public partial class Publicacion
{
    public Publicacion()
    {
        this.Edictos = new HashSet<Edictos>();
    }

    [Key]
    public decimal IdPublicacion { get; set; }
    public System.DateTime FechaPublicacion { get; set; }
    public string IdUsuario { get; set; }
    public System.DateTime FechaPublicacionHasta { get; set; }
    public System.DateTime FechaArchivoHasta { get; set; }
    public int IdSuscriptor { get; set; }
    public decimal IdTipoPublicacion { get; set; }

    [ForeignKey("IdSuscriptor")]
    public virtual Suscriptores Suscriptores { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当尝试运行此查询时:

public ActionResult DetailsVSTO(string Identificacion)
{
    var SusQ = from s in db.Suscriptores
               where s.Identificacion == Identificacion
               select s;

    return Json(SusQ.First(), JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

它抛出这个消息:

System.Data.SqlClient.SqlException:无效的列名称'Suscriptores_IdSuscriptor1'

为了解决这个问题,我在DBCOntext上添加了这个流利的内容

modelBuilder.Entity<Suscriptores>()
    .HasMany(x => x.Publicacion)
    .WithRequired(x => x.Suscriptores)
    .Map(a => a.MapKey("IdSuscriptor"));
Run Code Online (Sandbox Code Playgroud)

但问题仍然存在.我该怎么做才能解决这个问题.

Rob*_*her 9

我收到了与非外键列相关的错误,浪费了太多时间试图找出错误.它在我的代码中,而不是在EF或数据库中.我只是觉得我打字了

this.Property(t => t.Revision).HasColumnName("Revision");
this.Property(t => t.DistributionClass).HasColumnName("DistributionClass");
Run Code Online (Sandbox Code Playgroud)

但我输入的是

this.Property(t => t.Revision).HasColumnName("Revision");
this.Property(t => t.Revision).HasColumnName("DistributionClass");
Run Code Online (Sandbox Code Playgroud)

我想我正在看上面的那条线t.Revision而不是t.DistributionClass.无论我看了多久,我都看不出自己的错误.如果幸运的话,这将节省一些其他可怜的灵魂.


zs2*_*020 7

尝试添加多对一映射.请使用纯Fluent API,您应该删除[ForeignKey]注释.

modelBuilder.Entity<Publicacion>()
            .HasRequired(x => x.Suscriptores)
            .WithMany(x => x.Publicacion);
Run Code Online (Sandbox Code Playgroud)

  • 您能解释一下为什么您说他们应该使用纯 Fluent API 吗?注释有什么问题? (3认同)

Ty *_* H. 5

我在我刚刚添加的属性(列)的项目表中遇到了这个问题,多么令人沮丧!

事实证明,我在 Order 的数据模型中有一个 List 属性,并且因为我没有在该配置中忽略它,所以它会在 Item 表中导致同样的问题。除非两个表都有同名的属性,否则这种情况不会发生,所以我必须这样做......无论如何我都应该这样做。

public OrderConfiguration() { Ignore(p => p.Items); }