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



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

我试图在我的数据库中创建一个新的记录与该信息,是否有任何方法来创建一个对象,而不指定参数中的主键?显然我没有从用户那里获取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 password, string email, 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://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=data-annotations

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

最新更新