gpt4 book ai didi

c# - Entity Framework Core 自动生成的指南

转载 作者:行者123 更新时间:2023-12-02 19:03:53 26 4
gpt4 key购买 nike

有人可以指导我吗?我希望表的 primeryKey 作为 guid 在插入时具有数据库生成的值.

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

但它给出了错误

The seed entity for entity type 'User' cannot be added because there was no value provided for the required property 'Id'.

这是我的实际模型类和 DbContxt 类:

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

[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime CreatedOn { get; set; } = DateTime.UtcNow;


[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? UpdatedOn { get; set; }

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime LastAccessed { get; set; }
}

public class User : BaseModel
{
[Required]
[MinLength(3)]
public string Name { get; set; }

[Required]
[MinLength(3)]
[EmailAddress]
public string Email { get; set; }

[Required]
[MinLength(6)]
public string Password { get; set; }
}

然后在 MyDbContext 中:

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

protected override void OnModelCreating(ModelBuilder mb)
{
base.OnModelCreating(mb);

mb.Entity<User>().HasData(
new User() { Email = "Mubeen@gmail.com", Name = "Mubeen", Password = "123123" },
new User() { Email = "Tahir@gmail.com", Name = "Tahir", Password = "321321" },
new User() { Email = "Cheema@gmail.com", Name = "Cheema", Password = "123321" }
);
}

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

请帮忙!

最佳答案

您遇到的问题并非特定于自动生成的 Guid。 任何自动生成的键值都会发生同样的情况,包括常用的自动增量(标识)列。

这是由特定的 Data Seeding 引起的(HasData) 要求:

This type of seed data is managed by migrations and the script to update the data that's already in the database needs to be generated without connecting to the database. This imposes some restrictions:

  • The primary key value needs to be specified even if it's usually generated by the database. It will be used to detect data changes between migrations.
  • Previously seeded data will be removed if the primary key is changed in any way.

请注意第一个项目符号。因此,虽然对于普通的 CRUD,您的 PK 会自动生成,但在使用 HasData Fluent API 时,您需要指定它,并且该值必须是常量(不会改变),所以您不能使用Guid.NewGuid()。因此,您需要生成几个 Guid,获取它们的字符串表示形式并使用如下所示的内容:

mb.Entity<User>().HasData(
new User() { Id = new Guid("pre generated value 1"), ... },
new User() { Id = new Guid("pre generated value 2"), ... },
new User() { Id = new Guid("pre generated value 3"), ... }
);

关于c# - Entity Framework Core 自动生成的指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53493025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com