代码之家  ›  专栏  ›  技术社区  ›  Zach

MVC4-通过ID递增的模型插入SQL行时出现问题

  •  1
  • Zach  · 技术社区  · 13 年前

    使用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;}
    

    非常感谢您的帮助! -扎克

    1 回复  |  直到 13 年前
        1
  •  0
  •   Community Mohan Dere    9 年前

    听起来像是你试图设置自动身份字段的值,但你不应该这样做。看看这是否有帮助: Autonumber with Entity Framework

    推荐文章