自动递增非键值实体框架核心2.0

编程入门 行业动态 更新时间:2024-10-26 16:21:51
本文介绍了自动递增非键值实体框架核心2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个对象,该对象的密钥存储为GUID以及friendlyID,如下所示:

I've got an object that has a key stored as a GUID as well as a friendlyID, like this:

public class Job { [Key] public Guid Id { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int FriendlyId { get; set; } public string Description { get; set; } }

但是,当我尝试使用更新方法更新描述时:

However when I try to update description using my update method:

public void Update(Job job, Job jobParam) { if (job == null) { throw new AppException("Job does not exist"); } //Update job properties job.Description = jobParam.Description; _context.Job.Update(job); _context.SaveChanges(); }

我收到一条错误消息:

System.Data.SqlClient.SqlException:无法更新标识列 "FriendlyId"

System.Data.SqlClient.SqlException: Cannot update identity column 'FriendlyId'

我已经确保正确的对象正在尝试更新,但是我不明白为什么在未更改的情况下friendlyID会尝试进行更新.在线查看时,我可以看到EF core 1.1中存在一个错误,该错误会导致此问题的发生,但与2.0或与密钥无关的值无关.

I've made sure that the correct object is trying to be updated, but I can't understand why friendlyID would try to get updated when it has not been changed. When looking online I can see that there was a bug in EF core 1.1 that would cause this issue to occur, but nothing about 2.0 or about a value that isn't a key.

推荐答案

在EF Core中生成的属性的确切行为仍在调整中. EF Core 2.0引入了两个新的属性元数据属性- BeforeSaveBehavior 和 AfterSaveBehavior .没有用于设置它们的数据注释/流利的API,默认情况下,它们会从值生成策略以及该属性是否为键的一部分中隐含.同时,它们会影响跟踪操作的行为.

The exact behavior of the generated properties in EF Core is still in a process of tweaking. EF Core 2.0 introduced two new property metadata properties - BeforeSaveBehavior and AfterSaveBehavior. There is no data annotation/fluent API for setting them and by default they are implied from value generating strategy and whether the property is part of the key. At the same time they affect the behavior of the tracking operations.

这里的问题是,对于不是部分的标识列(即ValueGeneratedOnAdd),AfterSaveBehavior是Save,这又使Update方法成为将其标记为已修改,从而生成错误的UPDATE命令.

The problem here is that for identity columns (i.e. ValueGeneratedOnAdd) which are not part of a key, the AfterSaveBehavior is Save, which in turn makes Update method to mark them as modified, which in turn generates wrong UPDATE command.

要解决此问题,您必须像这样设置AfterSaveBehavior(在OnModelCreating替代内):

To fix that, you have to set the AfterSaveBehavior like this (inside OnModelCreating override):

modelBuilder.Entity<Job>() .Property(e => e.FriendlyId) .ValueGeneratedOnAdd() .Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw; // <--

更多推荐

自动递增非键值实体框架核心2.0

本文发布于:2023-11-14 16:39:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:键值   实体   框架   核心

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!