简体   繁体   English

ASP.Net 错误 System.InvalidOperationException

[英]ASP.Net error System.InvalidOperationException

I'm trying to make application where i can manage customers.我正在尝试制作可以管理客户的应用程序。 So i created database and table tecnici where I can insert all my technicians.所以我创建了数据库和表 tecnici,我可以在其中插入我所有的技术人员。

All CRUD operations worked until I created table clienti to insert my clients.在我创建表clienti来插入我的客户之前,所有 CRUD 操作都有效。 I made controller, model and view for clienti , and when i run the application it gives me this error System.InvalidOperationException: 'The entity type 'Cliente' requires a primary key to be defined.我制作了 controller、model 并查看了clienti ,当我运行应用程序时它给了我这个错误System.InvalidOperationException: '实体类型'Cliente'需要定义一个主键。 If you intended to use a keyless entity type call 'HasNoKey()'.'如果您打算使用无密钥实体类型,请调用“HasNoKey()”。

Error in ClientiController and it gaves me the same error when I try to load all clients ftom table clienti errore in TecniciController ClientiController中的错误,当我尝试在 TecniciController 中加载所有客户端 ftom table clienti errore时,它给了我同样的错误

This is code for ClientiController这是 ClientiController 的代码

public class ClientiController: Controller
    {
        private readonly AppDbContext _db;

        public ClientiController(AppDbContext db)
        {
            _db = db;
        }

        public IActionResult Index()
        {
            var datiClienti = _db.tboClienti.ToList();
            return View(datiClienti);
        }

        public IActionResult CreareCliente()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreareCliente(Cliente cliente)
        {
            if (ModelState.IsValid)
            {
                _db.Add(cliente);
                await _db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(cliente);
        }
    }

This is model Cliente这是 model 客户

public class Cliente
    {
        [Required(ErrorMessage = "Inserisci il nome di proprietario della azienda")]
        [Display(Name = "Nome")]
        public string Nome { get; set; }

        [Required(ErrorMessage = "Inserisci il cognome di proprietario della azienda")]
        [Display(Name = "Cognome")]
        public string Cognome { get; set; }

        [Display(Name = "Azienda")]
        public string Nome_azienda { get; set; }

        [Required(ErrorMessage = "Inserisci numero  cellulare della Azienda")]
        [DataType(DataType.PhoneNumber)]
        [Display(Name = "Telefono")]
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
           ErrorMessage = "Numero non valido")]
        public string Cellulare { get; set; }
    }

I have my connectionstring into appsettings.json我将连接字符串放入appsettings.json

And this is the calass where I configure db:这是我配置数据库的地方:

public class AppDbContext: DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options): base (options)
        {

        }

        public DbSet<Tecnico> tboTecnici { get; set; }
        public DbSet<Cliente> tboClienti { get; set; }
    }

Until was only one table (table: tecnici ) it did not make me problems.直到只有一张桌子(桌子: tecnici )它没有给我带来问题。 When I create controller model and view for table tboClienti it gives me the error.当我创建 controller model 并查看表 tboClienti 时,它给了我错误。

This is table tboClienti这是表 tboClienti

And this is tboTecnici这是 tboTecnici

Any suggestions how to fix this.任何建议如何解决这个问题。 Thanks in advance!提前致谢!

Try defining a primary key in your client class.尝试在客户端 class 中定义主键。

[Key]
public int Id { get; set; }

As the exception text says you have to define a primary key or explicitly say that this table has no primary key.正如异常文本所说,您必须定义主键或明确表示该表没有主键。

I suggest you to make a key like我建议你做一个像

[Key]
public int Id { get; set; }

or with a Guid instead of the integer - that has the advantage that Guids can be generated before saving but it is less readable than a number - as you want.或使用 Guid 而不是 integer - 其优点是可以在保存之前生成 Guid,但它的可读性不如数字 - 如您所愿。

[Key]
public Guid Id { get; set; }

You should specify that the column Id is your primary key, and also specify that is auto incremented by the SQL server您应该指定列Id是您的主键,并指定由 SQL 服务器自动递增

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

That way once you save your entity to the database, the Id will be automatically populated with the new generated value这样,一旦您将实体保存到数据库中, Id将自动填充新生成的值

If you face this Error and the [Key] Attribute didn't solve the issue.如果您遇到此错误并且 [Key] 属性没有解决问题。

You can try including the column order feature.您可以尝试包括列顺序功能。 This solves EntityType of No Key Defining Errors.这解决了无键定义错误的 EntityType。

[Key]
[Column(Order = 1)]
public int Id { get; set; } 

Include System.ComponentModel.DataAnnotations namespace in your Model Class.在 Model Class 中包含System.ComponentModel.DataAnnotations命名空间。

The key needs to be property and public. key需要是财产和公共。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:ASP.NET WebAPI中的System.InvalidOperationException - Error: System.InvalidOperationException in ASP.NET WebAPI System.InvalidOperationException:无法解析 ASP.NET Core 中的服务 - System.InvalidOperationException: Unable to resolve service in ASP.NET Core ASP.NET 核心 API System.InvalidOperationException 在本地化 - ASP.NET Core API System.InvalidOperationException in localization EF继续抛出错误System.InvalidOperationException ASP.NET MVC - EF keep throwing error System.InvalidOperationException ASP.NET MVC ASP.NET 错误:内部服务器错误:System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Error: Internal Server Error: System.InvalidOperationException: Unable to resolve service for type while attempting to activate ASP.NET Core 6 Web API 的集成测试抛出 System.InvalidOperationException - Integration test for ASP.NET Core 6 web API throws System.InvalidOperationException Asp.net 核心System.InvalidOperationException: 无法追踪实体类型x的实例 - Asp.net core System.InvalidOperationException: The instance of entity type x cannot be tracked ASP.NET Web服务:身份验证失败。 ExceptionType“:” System.InvalidOperationException” - ASP.NET WebService: Authentication failed. ExceptionType“:”System.InvalidOperationException" 执行OnRowCommand(ASP.NET)后未给出名称的System.InvalidOperationException - System.InvalidOperationException with no name given after executing an OnRowCommand (ASP.NET) System.InvalidOperationException:无法在数据迁移中的asp.net mvc 6上解析EF7中的项目“ ef” - System.InvalidOperationException: Unable to resolve project 'ef' in EF7 at asp.net mvc 6 in data migration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM