我是 EF 的新手,所以开始吧。我有一个包含以下内容的类
public class EmailTemplate
{
public Guid Id { get; set; }
[MaxLength(2000)]
public string Html { get; set; }
}
这是我的映射类
class EmailMapper : EntityTypeConfiguration<EmailTemplate>
{
public EmailMapper()
{
ToTable("EmailTemplate");
HasKey(c => c.Id);
Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(c => c.Id).IsRequired();
}
}
我正在尝试调用 DbContext.SaveChanges()
,但出现以下错误:
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'AutoSendConnection.dbo.EmailTemplates'; column does not allow nulls. INSERT fails.
我做错了什么?为什么 EF 不自动创建唯一的 GUID?
最佳答案
只需如下所示装饰 EmailTemplate 类中的 Id 字段,SQL Server 将在插入时自动生成值。
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
您也可以删除您的 Mapper 类,因为它不再需要了。
关于c# - Entity Framework 自动生成 GUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25094711/