バグの原因を特定するために、次のものを作成しました。
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 を使用できますか?