Entity Framework: complains of null id when entity id is set in code during SaveChanges
Lets assume the following code handling the SaveChanges event of a DataContext
void Context_SavingChanges(object sender, EventArgs e)
{
IEnumerable<ObjectStateEntry>开发者_JAVA百科; objectStateEntries =
from ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
where ose.Entity != null
select ose;
foreach (ObjectStateEntry entry in objectStateEntries)
{
foreach (var field in entry.CurrentValues.DataRecordInfo.FieldMetadata)
{
var guid = Guid.NewGuid();
AuditEntry audit = AuditEntry.CreateAuditEntry(
id: guid,
entitySet: entry.EntitySet.Name,
typeName: entry.Entity.GetType().Name,
entityId: (entry.CurrentValues["Id"] as string) ?? ((entry.State == EntityState.Added) ? "New" : null),
oldValue: (entry.State != EntityState.Added) ? entry.OriginalValues[field.FieldType.Name].ToString() : "New",
newValue: (entry.State != EntityState.Deleted) ? entry.CurrentValues[field.FieldType.Name].ToString() : "Deleted",
modifier: Environment.UserDomainName + "\\" + Environment.UserName,
dbAction: Enum.GetName(typeof(EntityState), entry.State),
field: field.FieldType.Name,
dateStamp: DateTime.Now
);
this.AuditEntries.AddObject(audit);
}
}
}
When I create a new Entity and attempt to save it's changes I get this error:
Cannot insert the value NULL into column 'Id', table 'TimeEF.dbo.AuditEntries'; column does not allow nulls. INSERT fails. The statement has been terminated.
When as you can see I have set the Id, any ideas? Bug?
Have you examined the id column of your object in the EDMX file? If its StoreGeneratedPattern attribute is marked as "computed" or "identity", then EF will not carry the C# value over to its SQL statement. Set the StoreGeneratedPattern attribute to "None" and the SQL that Entity Framework writes will contain your C#-created value for id.
<EntityType Name="AuditEntry">
//...
<Property Name="id" Type="int" Nullable="false" StoreGeneratedPattern="None" />
//...
</EntityType>
For more information, see http://msdn.microsoft.com/en-us/library/dd296755(v=vs.90).aspx.
精彩评论