2011-04-12 53 views
1
[Column(Name = "id", IsPrimaryKey = true, CanBeNull = false)] 
public string id { get; set; } 

错误:LINQ到SQL插入主键索引

Cannot insert the value Null into column id, column does not allow nulls

如果我将其设置为标识列,并在我的[Column attributes]我结束了一个IDENTITY一些变化嵌件未启用的错误,是什么我应该怎么做?我是否也需要我的主键列作为身份?

这只是一个简单的表+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 
    { 

    } 
+1

你为什么设置主键?我的意思是不是你正在使用的数据库提供主键? – Bastardo 2011-04-12 20:58:36

+0

我不需要设置isPrimaryKey吗?我以为我做了 – Baconbeastnz 2011-04-12 23:40:08

+0

好吧,如果你有一个数据库和一些表格,并且使用Sql Server或者Oracle等等你不需要。你可以在这些程序中设置它们,并在你的表中提供主键。 – Bastardo 2011-04-13 03:48:33

回答

0

如果我只是定义我IDIsPrimaryKey = trueIsDbGenerated = 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对象 - 电话后,即,我回来了真正的ID数据库已经给我的新实体。

所以我的问题是:你的问题在哪里呢?它似乎工作得很好....

+0

嘿!感谢现在为我工作的答复:-)一定是其中一个属性的措辞,父母现在被添加到数据库但孩子不是?我错过了什么?我已经将我的完整代码添加到顶端:) – Baconbeastnz 2011-04-12 23:16:23

+0

干杯!对于迟到的回复感到抱歉 – Baconbeastnz 2011-04-15 04:03:43

+0

为什么使用负数? – 2012-02-21 21:43:29