如何在实体框架中为 GUID 设置 NewId()

编程入门 行业动态 更新时间:2024-10-19 17:18:10
本文介绍了如何在实体框架中为 GUID 设置 NewId()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在创建 asp mvc4 示例.在这个示例中,我在数据上下文示例表中创建了 Id 列作为 GUID.

I am creating asp mvc4 sample.In this i created Id column as GUID in Sample table of datacontext.

public class Sample { [Required] public Guid ID { get; set; } [Required] public string FirstName { get; set; } }

这是实体表

CreateTable( "dbo.Samples", c => new { ID = c.Guid(nullable: false), FirstName = c.String(nullable: false) }) .PrimaryKey(t => t.ID);

ID 传递 00000000-0000-0000-0000-000000000000.

Id pass 00000000-0000-0000-0000-000000000000.

如何将 newid() 设置为 GUID 以及我必须设置的位置.

How to set newid() to GUID and where i have to set.

推荐答案

我建议您只使用 long 作为您的 ID 类型.它仅适用于"并比 GUID 有一些性能提升.但是如果你想使用 GUID,你应该使用 Sequential-guids">Sequential GUID 并在构造函数中设置它.我还将 ID 设为 private setter:

I would recommend just using long for your ID type. It "just works" with and has some performance gains over GUID. But if you want to use a GUID, you should use a Sequential GUID and set it in the constructor. I would also make ID a private setter:

public class Sample { public Sample() { ID = GuidComb.Generate(); } [Required] public Guid ID { get; private set; } [Required] public string FirstName { get; set; } }

顺序 GUID

public static class GuidComb { public static Guid Generate() { var buffer = Guid.NewGuid().ToByteArray(); var time = new DateTime(0x76c, 1, 1); var now = DateTime.Now; var span = new TimeSpan(now.Ticks - time.Ticks); var timeOfDay = now.TimeOfDay; var bytes = BitConverter.GetBytes(span.Days); var array = BitConverter.GetBytes( (long)(timeOfDay.TotalMilliseconds / 3.333333)); Array.Reverse(bytes); Array.Reverse(array); Array.Copy(bytes, bytes.Length - 2, buffer, buffer.Length - 6, 2); Array.Copy(array, array.Length - 4, buffer, buffer.Length - 4, 4); return new Guid(buffer); } }

更多推荐

如何在实体框架中为 GUID 设置 NewId()

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

发布评论

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

>www.elefans.com

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