我如何prevent的LINQ从增加一个GUID,使SQL Server可以做到这一点?这一点、可以做到、LINQ、prevent

2023-09-06 04:59:07 作者:暖阳

我创建和填充的LINQ to SQL对象编程,然后将它们添加到SQL Server数据库的PK uniqueidentifier列。 LINQ是自动分配全0的PK。这对插入产生错误,因为PK是重复的。

 暗淡myNewRecord为IceCreamTrackerTable
myNewRecord.name =鲍伯
myNewRecord.favoriteIceCream =香草
   myNewRecord.PK = 00000000-0000-0000-0000-000000000000(默认)
myDataContext.IceCreamTrackerTables.insertOnSubmit(myNewRecord)
    '第二条记录添加抛出一个错误,因为它也有PK 00000等。
 

在我知道我可以使用myNewRecord.pk = Guid.newGuid分配PK() GUID是全0(零)? 但我真正想要的是SQL服务器被分配,因为我假设它有一些方法,以确保它不重新分配的GUID相同的GUID

有没有办法告诉LINQ,我不希望填补GUID自己,但离开它的SQL Server?

解决方案

的GUID是值类型,因此,他们不能为空。这意味着在创建的Guid时,它有分配缺省值(这是所有0)。 SQL Server不会自动生成GUID的主键像它的标识列。您可以设置默认值NEWID(),但默认情况下EF会忽略这一点,尝试插入值。你可以做一些喜欢这里描述覆盖此

http://softmindit.blogspot.com/ P /使用-GUID-AS-的EntityKey功能于entity.html

编辑:我只是你正在使用LINQ to SQL的不LINQ到实体实现的。但是,我敢肯定有一个在L2S类似的东西来处理这个问题。

EDIT2:有一个类似的事情在LINQ to SQL中,如截图所示。更改此属性解决了这个问题。

DBLinq之Linq to mysql

I am creating and filling LINQ to SQL objects programatically and then adding them to a sql server database with a uniqueidentifier column for a PK. LINQ is automatically assigning a PK of all 0s. This creates errors upon insert because the PK is a duplicate.

Dim myNewRecord as IceCreamTrackerTable
myNewRecord.name=Bob
myNewRecord.favoriteIceCream=Vanilla
   'myNewRecord.PK=00000000-0000-0000-0000-000000000000 (by default)'
myDataContext.IceCreamTrackerTables.insertOnSubmit(myNewRecord)
    ''second record added throws an error because it also has PK 00000 etc. 

I know that I can assign the PK using myNewRecord.pk=Guid.newGuid() Guid is all 0's (zeros)? But what I really want is for SQL server to be assigning the GUIDs because I'm assuming that it has some method to make sure that it is not re-assigning the same guid

Is there any way to tell LINQ that I don't want to fill the GUID myself but leave it up to SQL server?

解决方案

Guid's are value types, thus they cannot be null. That means when a Guid is created, it has to assign a default value (which is all 0's). SQL Server does not automatically generate GUID's for primary keys like it does for Identity columns. You can set the default value to NEWID(), but by default EF will ignore that and try to insert a value. You can override this by doing something like described here

http://softmindit.blogspot.com/p/using-guid-as-entitykey-in-entity.html

EDIT: I just realized you're using Linq to sql not Linq to entities. However, i'm sure there's something similar in L2S to deal with this.

Edit2: There is a similar thing in linq to sql, as shown in the screenshot. Changing this property fixes the problem