【问题标题】:EntityType X has no key defined. Define the key for this EntityTypeEntityType X 没有定义键。定义此 EntityType 的键
【发布时间】:2016-06-20 22:18:55
【问题描述】:

所以我试图通过调用静态类方法将实体保存在数据库中,我已将要保存的对象传递给该方法:

static public Room saveTheatherRoom(Room theatherRoom)
{
        using (var db = new ThetherDBContext())
        {
            db.Rooms.Add(theatherRoom);                                
            db.SaveChanges();
            return theatherRoom;
        }
}

在线db.Rooms.Add(theatherRoom);我得到以下异常:

    System.Data.Entity.ModelConfiguration.ModelValidationException was unhandled
  HResult=-2146233088
  Message=One or more validation errors were detected during model generation:

Theather.Image: : EntityType 'Image' has no key defined. Define the key for this EntityType.
Theather.ImageList: : EntityType 'ImageList' has no key defined. Define the key for this EntityType.
Theather.ToolStripItem: : EntityType 'ToolStripItem' has no key defined. Define the key for this EntityType.
Theather.Control: : EntityType 'Control' has no key defined. Define the key for this EntityType.
Theather.PrintDocument: : EntityType 'PrintDocument' has no key defined. Define the key for this EntityType.
Theather.PageSettings: : EntityType 'PageSettings' has no key defined. Define the key for this EntityType.
Theather.NumericUpDownAcceleration: : EntityType 'NumericUpDownAcceleration' has no key defined. Define the key for this EntityType.
Theather.DataGridViewCellStyle: : EntityType 'DataGridViewCellStyle' has no key defined. Define the key for this EntityType.
Theather.DataGridViewCell: : EntityType 'DataGridViewCell' has no key defined. Define the key for this EntityType.
Theather.DataGridViewRow: : EntityType 'DataGridViewRow' has no key defined. Define the key for this EntityType.
Theather.ListViewItem: : EntityType 'ListViewItem' has no key defined. Define the key for this EntityType.
Theather.CultureInfo: : EntityType 'CultureInfo' has no key defined. Define the key for this EntityType.
Theather.DateTimeFormatInfo: : EntityType 'DateTimeFormatInfo' has no key defined. Define the key for this EntityType.
Theather.TreeNode: : EntityType 'TreeNode' has no key defined. Define the key for this EntityType.
GridItems: : The referenced EntitySet 'GridItems' for End 'GridEntry_ParentGridEntry_Source' could not be found in the containing EntityContainer.
GridItems: : The referenced EntitySet 'GridItems' for End 'GridEntry_ParentGridEntry_Target' could not be found in the containing EntityContainer.
LayoutSettings: : The referenced EntitySet 'LayoutSettings' for End 'TableLayoutPanel_LayoutSettings_Target' could not be found in the containing EntityContainer.
Images: EntityType: EntitySet 'Images' is based on type 'Image' that has no keys defined.
ImageLists: EntityType: EntitySet 'ImageLists' is based on type 'ImageList' that has no keys defined.
ToolStripItems: EntityType: EntitySet 'ToolStripItems' is based on type 'ToolStripItem' that has no keys defined.
Controls: EntityType: EntitySet 'Controls' is based on type 'Control' that has no keys defined.
PrintDocuments: EntityType: EntitySet 'PrintDocuments' is based on type 'PrintDocument' that has no keys defined.
PageSettings: EntityType: EntitySet 'PageSettings' is based on type 'PageSettings' that has no keys defined.
NumericUpDownAccelerations: EntityType: EntitySet 'NumericUpDownAccelerations' is based on type 'NumericUpDownAcceleration' that has no keys defined.
DataGridViewCellStyles: EntityType: EntitySet 'DataGridViewCellStyles' is based on type 'DataGridViewCellStyle' that has no keys defined.
DataGridViewCells: EntityType: EntitySet 'DataGridViewCells' is based on type 'DataGridViewCell' that has no keys defined.
DataGridViewRows: EntityType: EntitySet 'DataGridViewRows' is based on type 'DataGridViewRow' that has no keys defined.
ListViewItems: EntityType: EntitySet 'ListViewItems' is based on type 'ListViewItem' that has no keys defined.
CultureInfoes: EntityType: EntitySet 'CultureInfoes' is based on type 'CultureInfo' that has no keys defined.
DateTimeFormatInfoes: EntityType: EntitySet 'DateTimeFormatInfoes' is based on type 'DateTimeFormatInfo' that has no keys defined.
TreeNodes: EntityType: EntitySet 'TreeNodes' is based on type 'TreeNode' that has no keys defined.
GridItems: EntityType: EntitySet 'GridItems' is based on type 'GridItem' that has no keys defined.
LayoutSettings: EntityType: EntitySet 'LayoutSettings' is based on type 'LayoutSettings' that has no keys defined.

这显然没有任何意义,因为我的数据库上下文或实体类中没有上述任何实体类型。

【问题讨论】:

  • 你的方法签名不应该先定义public然后static吗?无论如何,我会设置一些断点并从头到尾逐步执行您的代码,并确保传递的值是您所期望的。还要确保 dbset Rooms 实际定义为 dbset {get; set;} 在 dbcontext 中
  • 感谢您的回答,但似乎错误是因为我继承了一个与 Windows 窗体组件无关的类,其基类也在数据库上下文中。
  • 我很高兴你知道了这一点。您应该为您自己的问题写一个简短的答案并附上解释,以便谷歌搜索此错误的其他人可能会发现您的解决方案很有帮助。
  • 谢谢,我添加了更详细的解决方案。

标签: c# entity-framework


【解决方案1】:

根据我的经验,ModelValidationException 错误通常可能是由于 DB 数据上下文中的表类中缺少 KeyAttribute,或者 Database.SetInitializerOnModelCreating 覆盖方法中被错误地初始化。

检查您是否满足以下条件:

如果您有 edmx(实体框架)或 dbml(LINQ to SQL),请确保所有表 类有KeyAttribute 来识别主键列属性。

using System.ComponentModel.DataAnnotations;

namespace Theater
{
    public class Room
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)] // only if your primary key is auto-generated/identity column
        [Key]
        public int RoomId { get; set; }
    }
}

其次,确保您的方法具有正确的“公共静态”顺序。

public static Room saveTheatherRoom(Room theatherRoom)
{
        using (var db = new ThetherDBContext())
        {
            db.Rooms.Add(theatherRoom);                                
            db.SaveChanges();
            return theatherRoom;
        }
}

然后,检查 DbContext 构造函数是否将“Rooms”作为 DbSet 属性。

public ThetherDBContext() : base("ConnectionName")
{
    public DbSet<Room> Rooms { get; set; }
}

CMIIW。

【讨论】:

  • 感谢您的回答,但似乎错误是因为我继承了一个与 Windows 窗体组件无关的类,其基类也在数据库上下文中。
【解决方案2】:

好的,错误是由以下原因引起的: 我从实体框架上下文文件中存在的类派生了一个帮助程序类。我没有尝试通过上下文将该帮助程序类的任何实例保存在数据库中,但 EF 还是以某种方式做到了。

派生类:

class SeatHelper : Seat
{
    public int typeId { get; set; }
    public bool seatPositionSet { get; set; }
    public PictureBox image { get; set; }
    public Point position { get; set; }
}

父类:

[Table("Seat")]
public partial class Seat
{
    public Seat()
    {
        ReservedSeats = new HashSet<ReservedSeat>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int seatId { get; set; }

... etc.

上下文文件:

public partial class ThetherDBContext : DbContext
{
    public ThetherDBContext()
        : base("name=ThetherDBContext")
    {
    }

    public virtual DbSet<Room> Rooms { get; set; }
    public virtual DbSet<TypeOfSeat> TypesOfSeats { get; set; }
    public virtual DbSet<Seat> Seats { get; set; } ... etc.

解决方案是从 SeatHelper 类中删除继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2016-03-16
    • 2013-08-04
    • 2012-12-10
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多