jjzjj

c# - 实体类型需要定义主键

coder 2024-05-28 原文

我现在正在编写一个 ASP.NET Web API,对于 2 个 Controller ,一切都运行良好。现在我尝试做与以前完全相同的事情,但这次我得到一个奇怪的错误:

System.InvalidOperationException: "The entity type 'UserItem' requires a primary key to be defined."

那么,为什么 UserItem 需要主键而其他的不需要?

这是我的 UserItem 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ModulApi.Models
{
    public class UserItem
    {
        public int matrikelnr { get; set; }
        public string studiengang { get; set; }
        public string user_semester { get; set; }
        public string user_max_klausur { get; set; }

        //Not necessary Constructor. I try to fix the primary Key error.
        public UserItem()
        {
            this.matrikelnr = 0;
            this.studiengang = "";
            this.user_max_klausur = "";
            this.user_semester = "";
        }
    }
}

还有我的工作 LoginItem 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ModulApi.Models
{
    public class LoginItem
    {
        public long Id { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string matrikelnr { get; set; }
        public string email { get; set; }
        public string email_verified { get; set; }

        public LoginItem()
        {
            this.Id = 0;
            this.username = "";
            this.password = "";
            this.matrikelnr = "";
            this.email = "";
            this.email_verified = "";
         }
    }
}

如您所见,我设置了 getter 和 setter,所以不会出现错误。

这里是错误发生的地方:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ModulApi.Models;
using ModulApi.DBConnectors;

// For more information on enabling Web API for empty projects, visit 
https://go.microsoft.com/fwlink/?LinkID=397860

namespace ModulApi.Controllers
{
    [Route("api/user")]
    public class UserController : Controller
    {
        private readonly UserContext _context;

        public UserController(UserContext context)
        {
            _context = context;

            if (_context.UserItems.Count() == 0)  <--- Error right here
            {
                 getDataFromConnector(_context);
            }
        }

        private void getDataFromConnector(UserContext context)
        {
            //Getting my Data from Database method
        }
        .
        .

好吧,因为它在 Context 调用中,我也会附加 UserContext,但它与 LoginContext 中的一样,工作得很好。

用户上下文:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace ModulApi.Models
{
    public class UserContext : DbContext
    {
        public UserContext(DbContextOptions<UserContext> options) : base(options)
        {
        }

        public DbSet<UserItem> UserItems { get; set; }
    }
}

有谁知道为什么我会收到这个奇怪的错误?为什么所有其他 Controller 都能正常工作,它们的功能完全相同?

最佳答案

Entity Framework 通过 convention 进行.这意味着如果您有一个对象具有名为 Id 的属性,它将假定它是该对象的主键。这就是为什么您的 LoginItem 类可以正常工作的原因。

您的 UserItem 类没有这样的属性,因此它无法确定将什么用作主键。

要解决此问题,请添加 KeyAttribute无论你的主键在你的课上是什么。例如:

// Need to add the following using as well at the top of the file:
using System.ComponentModel.DataAnnotations;

public class UserItem
{
    [Key]
    public int matrikelnr { get; set; }
    public string studiengang { get; set; }
    public string user_semester { get; set; }
    public string user_max_klausur { get; set; }

    // ...
}

关于c# - 实体类型需要定义主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48225989/

有关c# - 实体类型需要定义主键的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  4. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  5. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  6. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

  7. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  8. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  9. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  10. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

随机推荐