如何在实体框架中创建新记录而不在其参数中指定主键?

问题描述

我的项目中有一个网页,其中有人注册成为用户。然后我的控制器从前端获取一个 api 调用,其中包含从注册中输入的帖子值。

我正在尝试使用该信息在我的数据库中创建一个新记录,有没有办法在不指定参数中的主键的情况下创建对象?我显然没有从用户那里获取 id,所以我只想创建没有 id 的对象。

控制器

// POST api/values
[HttpPost]
public void Post(string username,string password,string email,string role)
{
    Users user = new Users(username,password,email,role);
    _repository.createuser(user);
    _repository.SaveChanges();
}

型号:

using System.ComponentModel.DataAnnotations;

namespace IssueTracker.Models
{
    public class Users
    {
        [Key]
        public int id { get; set; }

        [required]
        public string username { get; set; }

        [required]
        public string password { get; set; }

        [required]
        public string email { get; set; }

        [required]
        public string role { get; set; }

        public Users(int id,string username,string role)
        {
            this.id = id;
            this.username = username;
            this.password = password;
            this.email = email;
            this.role = role;
        }

        public Users()
        {
        }
    }
}

解决方法

如果您在 SQL Server 中的表被定义为具有 Id INT IDENTITY 列 - 那么是的,SQL Server 将自动处理创建新的 PK。您需要向模型中的 Id 列添加另一个属性:

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

    [Required]
    public string username { get; set; }

    // other properties here .....
}

这告诉 EF SQL Server 数据库将为 Id 创建一个新的唯一值,该值将用作 User 对象的主键。

,

没有PK是不明智的,但您可以使用[Keyless]属性并删除Id字段。

更多信息: https://docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=data-annotations

如果您想为 Id 自动生成值以便您不需要指定它,请检查: https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations