实体框架中的增量字段取决于另一个字段的值 [英] increment field in entity framework depending on value of another field

查看:124
本文介绍了实体框架中的增量字段取决于另一个字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Entity Framework中是新的,我有一些在纯t-sql中很容易的东西的问题。假设我们有3列的表。 Id(身份,主键),IdKind(int),Number(int)。 Nubmer列依赖于IdKind列。此表中的数据应如下所示:



Id | IdKind |号码



1 | 1 | 1



2 | 1 | 2



3 | 1 | 3



4 | 2 | 1



5 | 2 | 2



6 | 2 | 3



您可以看到列号自动递增取决于IdKind。在t-sql中,我为某些IdKind找到max(Number)+ 1。一个事务中的一切存储过程都是一个,所以Number的值对于IdKind是唯一的。



如何在Entity Framework中完成相同的操作。应该在创建新对象或更改IdKind时计算Number的值。

解决方案

我将使用数据库触发器,并配置 Number 属性在EF映射中与 StoreGeneratedPattern.Computed 通知EF该属性已在数据库中填充,并且必须在每个更新/插入。



我也不会对每个新的数字使用max()。相反,我将维护单独的表模拟序列。此表格应包含每个序列的记录 - 在您的案例记录中,每个 IdKind 具有当前最大数量。而不是选择聚合,您将选择单个记录,并将其更新为包含新的最大数量。使用此表格必须在与实体的持久更改相同的事务中。


I'm new in Entity Framework and i have problem with something which was quite easy in pure t-sql. Assume that we have table with 3 columns. Id(identity, primary key), IdKind (int), Number(int). Column Nubmer depends on IdKind column. Data in this table should look like this:

Id | IdKind | Number

1 | 1 | 1

2 | 1 | 2

3 | 1 | 3

4 | 2 | 1

5 | 2 | 2

6 | 2 | 3

As you can see column number is auto incremented depends on IdKind. In t-sql I was finding max(Number) + 1 for some IdKind. Everything was in one stored procedure in one transaction so value of Number was unique for IdKind.

How to accomplish the same in Entity Framework. Value of Number should be computed when creating new object or when changing IdKind.

解决方案

I would use database trigger for that and configure Number property in EF mapping with StoreGeneratedPattern.Computed to inform EF that this property is filled in the database and must be reloaded after each update / insert.

I would also not use max() for each new number. Instead I would maintain separate table simulating sequences. This table should contain record per sequence - in your case record per IdKind with current max number. Instead of selecting aggregation you will select single record and update it to contain new max number. Working with this table must be in the same transaction as persisting changes to your entity.

这篇关于实体框架中的增量字段取决于另一个字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆