使用MVC4时,我在向数据库(SQL Compact)中插入新行时遇到了一些问题。我从原始文本(制表符分隔)构建行,如下所示:
while (reader.Peek() != -1)
{
newRow = Cos.Create();
line = reader.ReadLine().Split('\t');
for (int i = 0; i < header.Count(); i++)
{
switch (header[i])
{
case "CompanyName":
newRow.CompanyName = line[i];
break;
case "City":
newRow.City = line[i];
break;
case "Country":
newRow.Country = line[i];
break;
default:
return "A column was found with an unacceptable value - " + header[i] + " - No changes have been made.";
}
}
this.Cos.Add(newRow);
}
this.SaveChanges();
我的表有一个Id列,设置为:int、Unique、Primary Key和Identity(种子:1,增量:1)。问题是SQL拒绝“this.SaveChanges()”生成的语句,因为我生成的所有行的Id值都是0。
有没有一种方法可以让SQL在插入时为每一行分配一个唯一的Id?我的理解是,这种方式是身份的目的。
我的模型看起来就是这样:
public class CoDB{
public string CompanyName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int Id { get; set; }
}
CoDBContext定义了:
public DbSet<CoDB> Cos {get; set;}
非常感谢您的帮助!
-扎克