[Column(Name = "id", IsPrimaryKey = true, CanBeNull = false)]
public string id { get; set; }
错误:
无法插入值Null 列id,列不允许空值
如果我将其设置为标识列并在我的[Column attributes]
中进行一些更改,我最终会出现IDENTITY insert not enabled错误,我该怎么办?我是否还需要我的主键列作为标识?
这只是一个简单的表,主键上有+1增量
public partial class linqtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyContext db = new MyContext("Server=(local);Database=Test;User ID=admin;Password=pw");
Child c = new Child();
c.name = "joe "+DateTime.Now;
db.parents.InsertOnSubmit(c);
db.SubmitChanges();
}
}
public class MyContext : DataContext
{
public static DataContext db;
public MyContext(string connection) : base(connection) { }
public Table<Parent> parents;
}
[Table(Name="parents")]
[InheritanceMapping(Code = "retarded", Type = typeof(Child), IsDefault=true)]
public class Parent
{
[Column(Name = "id", IsPrimaryKey = true, CanBeNull = false, DbType = "Int NOT NULL IDENTITY", IsDbGenerated = true)] /* I want this to be inherited by subclasses */
public int id { get; set; }
[Column(Name = "name", IsDiscriminator = true)] /* I want this to be inherited by subclasses */
public string name { get; set; }
}
public class Child : Parent
{
}
答案 0 :(得分:0)
如果我只是将ID
列定义为IsPrimaryKey = true
和IsDbGenerated = true
,那么一切正常:
[ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert,
DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int ID
{....}
然后,在代码中 - 当我创建一个新实体时,我只是为实体分配一个任意ID
- 我通常倾向于使用负数:
MyEntity entity = new MyEntity { ID = -55 };
MyContext.MyEntities.InsertOnSubmit(entity);
MyContext.CommitChanges();
在调用.CommitChanges()
之后,新实体存储在数据库表中,实际的真实ID
值(INT IDENTITY
)正在设置并反映在我的{entity
上1}} object - 即在调用之后,我回到数据库为我的新实体提供的真实ID
。
所以我的问题是:你的问题在哪里?它似乎工作得很好....