为了尝试隔离错误的来源,我构建了以下内容:
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 为空(全为零)
为什么会这样?EF 可以与数据库生成的 Guid 一起使用吗?