C# EntityFramwork 6-调用SaveChanges()时未设置ID
我的实体框架有点问题。 我的设置如下: 我使用的是代码优先迁移,这是数据库结构:C# EntityFramwork 6-调用SaveChanges()时未设置ID,c#,mysql,entity-framework,azure,entity-framework-6,C#,Mysql,Entity Framework,Azure,Entity Framework 6,我的实体框架有点问题。 我的设置如下: 我使用的是代码优先迁移,这是数据库结构: using Microsoft.Azure.Mobile.Server; namespace myProject.DataObjects { public class ListRelations : EntityData { public string userID { get; set; } public bool read { get; set; }
using Microsoft.Azure.Mobile.Server;
namespace myProject.DataObjects
{
public class ListRelations : EntityData
{
public string userID { get; set; }
public bool read { get; set; }
public bool write { get; set; }
}
}
现在从EnitityData导入应该添加ID字段和所有元数据,对吗?
当我尝试这样填充数据库时:
var relations = new ListRelations();
relations.userID = currentUser;
relations.read = true;
relations.write = true;
relations.listID = current.Id;
context.ListRelationsSet.Add(relations);
try {
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
我收到错误,说需要填充ID字段。
但是,数据库不应该为我这样做吗?
我有点困惑,
欢迎任何帮助 使用
public class ListRelations : EntityData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity),
Column(TypeName = "varchar"),
MaxLength(20),
Key]
public string userID { get; set; }
public bool read { get; set; }
public bool write { get; set; }
}
这取决于您的数据库提供程序,但例如,T-Sql有一个名为newsequentialid()
的过程来帮助填充此类列
迁移中的示例使用可以是
Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),
EnitityData
中有什么?这个:类型是string
,数据库无法为您填充它(如果您理解我的意思,这不是身份)@IvanStoev我明白了,但这不是很愚蠢吗?EntityData是这样使用的,不是吗?老实说,听起来很愚蠢:)但我从来没有使用过,也不知道使用EntityData
类有什么好处。再深入一点,据说通过注释设置默认值约束将在EF 7中得到支持。在此之前,我们似乎必须手动修改迁移