Ids实体框架代码的最佳实践 [英] Best practice for Ids Entity framework code first

查看:118
本文介绍了Ids实体框架代码的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我今天早些时候绊倒了这篇文章
https://blogs.msdn.microsoft.com/azuremobile/2014/05/22/tables-with-integer-keys-and-the-net-backend/

So I stumbled upon this article earlier today https://blogs.msdn.microsoft.com/azuremobile/2014/05/22/tables-with-integer-keys-and-the-net-backend/

在文章中,作者发表了评论,引起了我的注意。他说

In the article, the author makes a comment that got my attention. He said

注意:通常,从.NET后端中的Entity Framework Code-First模型开始,您将使用字符串ID

Note: Typically, when starting from an Entity Framework Code-First model in your .NET Backend, you would use string ids

从我所看到的,使用字符串ID可能是一个性能问题,因为您的表增长。所以我只想知道这只是作者的意见,还是一个标准。如果是后期,我想知道这个背后的原因。

From what I've read, using string Ids can be a performance issue in as your table grows. So I would just like to know if this was just the authors opinion or it is a standard. If it is the later, I would like to know the reasons behind this.

推荐答案

技术上是的,你可以使用字符串作为主键,但如果一个字符串是有道理的,那么你应该用它。你必须考虑一下你的帐户。

Technically yes, you can use the string as primary key, but if a string makes sense to be the primary key then you should probably use it. You have to take in your account some consideration.


  • Digtis比较速度比字符串比较快

  • Digtis comparison is faster then string comparison

较长的字符串意味着难以比较

Longer string mean harder to compare

当您必须使用字符串作为主键,然后设置长度例如MaxLength = 20 = nvarchar(20)

When you must use a string as primary key then set the length e.g. MaxLength = 20 = nvarchar(20)

  public class User
  {
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None), MaxLength(20)]
    public string UserId { get; set; }
    ....

这将帮助您避免一些性能问题。
您还可以使用dbcontext.executesqlcommand将生成的密钥从nvarchar更改为varchar,这将为您提供更多空间(一个字符将仅使用一个字节而不是2)。

This will help you to avoid some performance issues. You can also change the generated key from nvarchar to varchar by using dbcontext.executesqlcommand this will give you more space (One charachter will use only one byte and not 2).

或者,您可以使用代码首先更改列数据类型如下:

Alternatively, you can with code first change the column data type as following:

[Key, DatabaseGenerated(DatabaseGeneratedOption.None), Column(TypeName = "varchar"), MaxLength(20)]
public string UserId { get; set; }
....

这篇关于Ids实体框架代码的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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