为了尽量我已经建立了以下错误的源隔离:
SQL Server表:
CREATE TABLE [dbo].[Names]
([Key] [uniqueidentifier] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Names] PRIMARY KEY CLUSTERED ([Key] ASC)
)
GO
ALTER TABLE [dbo].[Names] ADD CONSTRAINT [DF_Names_Key] DEFAULT (newid()) FOR [Key]
当我通过SQL Server Management Studio中添加行到该表中的GUID得到预期的值。
然后创建与此表的EF模型,产生下面的代码:
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="Model1", Name="Names")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Names : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Names object.
/// </summary>
/// <param name="key">Initial value of the Key property.</param>
public static Names CreateNames(global::System.Guid key)
{
Names names = new Names();
names.Key = key;
return names;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Guid Key
{
get
{
return _Key;
}
set
{
if (_Key != value)
{
OnKeyChanging(value);
ReportPropertyChanging("Key");
_Key = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Key");
OnKeyChanged();
}
}
}
private global::System.Guid _Key;
partial void OnKeyChanging(global::System.Guid value);
partial void OnKeyChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Name
{
get
{
return _Name;
}
set
{
OnNameChanging(value);
ReportPropertyChanging("Name");
_Name = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Name");
OnNameChanged();
}
}
private global::System.String _Name;
partial void OnNameChanging(global::System.String value);
partial void OnNameChanged();
然后,我创建了一个测试将数据添加到表:
[TestMethod]
public void WriteTestMethod1()
{
using (Model1Container context = new Model1Container())
{
Names n = new Names();
n.Name = "T2";
context.Names.AddObject(n);
context.SaveChanges();
}
}
这样做的结果是,该行被插入,但GUID是空的(全0)
这究竟是为什么?能加速转发数据库的工作生成的GUID?
这是旧的,但这里是一个答案,无论如何,因为它仍然是相关的。
class Names
的实例,并赋值给Name
财产。您可以通过定义键字段为空,将在Guid?
的C#(而不是Guid
)与字段类型对应得到一个服务器生成的UID值。然后,你可以允许把键值改为你的代码保持零和服务器定义的默认表情将被使用。
然而,如果该字段是主键,可为空场可能不是你所需要的。当我在这种情况下是我用一个构造函数,设置一个GUID值(是的,在客户端),而不是允许其采取的默认值。