简体   繁体   English

如何使用LINQ将Guid存储在uniqueidentifier SQL字段中?

[英]How can i store a Guid in a uniqueidentifier SQL field with LINQ?

I create manually my GUID for storing it to database like so 我手动创建GUID以便像这样将其存储到数据库

Guid EmailToken = Guid.NewGuid;

I tried to store it in an uniqueidentifier field of SQL with LINQ like 我试图用LINQ将其存储在SQL的uniqueidentifier字段中,例如

using (DBDataContext DB = new DBDataContext()) {
    Member M = new Member { ActEmlGuid = EmailToken };
    DB.Members.InsertOnSubmit(M);
    DB.SubmitChanges();
}

Unfortunately the SQL now has a different GUID than the one i created. 不幸的是,SQL现在的GUID与我创建的GUID不同。 Why is this happening? 为什么会这样呢? How can i overcome this? 我该如何克服呢? I do not want SQL to create the GUID for me. 我不希望SQL为我创建GUID。

And here are the properties of the SQL field 这是SQL字段的属性

在此处输入图片说明

ok chocol8 (grt name btw!!). 好的chocol8(名字叫btw !!)。

if you are using EF code first, you can add the following to your model on the guid. 如果首先使用EF代码,则可以在GUID上将以下内容添加到模型中。

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ActEmlGuid { get; set; }

This will enable sqlserver (server-side) guid generation, thus enabling you to use the correct field types as planned. 这将启用sqlserver(服务器端)guid生成,从而使您能够按计划使用正确的字段类型。

It's a tricky little nut this one, as so much depends on the mechanics of your interaction with the db, but hopefully the above will act as a guide in some way, otherwise, my nutty .ToString() option (mentioned in comments) may get you out of a tangle in the short-term -tho of course not advisable. 这有点棘手,因为这很大程度上取决于您与数据库交互的机制,但是希望以上内容可以以某种方式充当指南,否则,我的nutty .ToString()选项(在注释中提到)可能在短期内让您摆脱困境-当然不建议这样做。

[edit] - if you are not using EF, then you can update your schema (in the properties page in your OP above) and add: [edit] -如果您不使用EF,则可以更新架构(在上述OP的属性页中)并添加:

在此处输入图片说明

Try this 尝试这个

Member M = new Member();
M.ActEmlGuid = Guid.NewGuid;
DB.Members.Add(M);
DB.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM