【问题标题】:EntityType has no key defined error, but I do have a key defined. Why is this failing?EntityType 没有键定义错误,但我确实定义了键。为什么会失败?
【发布时间】:2014-11-02 07:09:05
【问题描述】:

我正在尝试将一个对象写入数据库,但它抛出了以下异常:

在模型生成过程中检测到一个或多个验证错误:

EntityType 'PageResponse' 没有键 定义。定义此 EntityType 的键。页面响应:实体类型: EntitySet 'PageResponse' 基于类型 'PageResponse' 没有 已定义键。

但我确实定义了一个键。为什么还是失败了?

这是我的代码:

public class PageContext : DbContext
{
    public PageContext()
        : base("DefaultConnection")
    {

    }

    public DbSet<PageResponse> PageResponse { get; set; }
}

[Table("PageResponse")]
public class PageResponse
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int PageResponseId;

    public Uri Uri { get; set; }
    public string Text { get; set; }

    public string Title { get; set; }

    public string OriginalUrl { get; set; }

    public Uri ResponseUri { get; set; }
}

using (var db = new PageContext())
{
    try
    {
        PageResponse pr = new PageResponse
        {
            Text = data.Text,
            Uri = data.Step.Uri,
            Title = data.Title,
            OriginalUrl = data.OriginalUrl,
            ResponseUri = data.ResponseUri,

        };

        db.PageResponse.Add(pr);
        db.SaveChanges();  

    }
    catch (Exception ex)
    {

    } 
}

【问题讨论】:

  • 不.. 直到你说了什么我才知道它的存在。我是不是该?还是我应该寻找一些东西?
  • 不,如果有帮助的话,它是一个控制台应用程序。我只在 MVC 应用程序中做过任何 EntityFramework 的事情。
  • 好吧...完全披露:这是 NCrawler 解决方案的一部分 (ncrawler.codeplex.com)。我正在尝试将实体框架引入我的本地项目,以便将一些东西写入我的本地数据库。但我不这么认为。我刚刚对“[Key]”进行了全局搜索,但在任何地方都没有看到。
  • 不,还是一样。
  • 终于发现了,清理了cmets!

标签: c# entity-framework


【解决方案1】:

您的 key 属性定义不正确,它没有 getter 或 setter。改变这个:

public int PageResponseId;

到这里:

public int PageResponseId { get; set; }

【讨论】:

  • 轰隆隆!做到了。我通常会指定 getter 和 setter,但这次我什至没有注意到它们不见了!好东西。我已经转向一个新错误Error retrieving values from ObjectStateEntry,但这是不同日子的不同问题。
猜你喜欢
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 2016-04-02
  • 2016-03-16
相关资源
最近更新 更多