写入的ID值不一致

时间:2018-04-19 07:50:00

标签: c# sql-server asp.net-core entity-framework-core ef-core-2.0

我正在努力解决这个问题。我有一个基本的CRUD应用程序。我有一个DbInitializer类来检查DB是否存在,如果没有,则添加3行。到目前为止这很好,因为这3条记录的ID是预期的1-3。

自从将ViewModel引入我的应用程序后,我的“创建”页面上添加的任何其他记录的数据库ID都为1002,2003等。我无法找到它的来源。

以下是相关表格:

Table with inconsistent ID values

这是我的DBInitializer类:

public class DbInitializer
{
    public static void Initialize(GymContext context)
    {
        context.Database.EnsureCreated();

        // Look for any students.
        if (context.Members.Any())
        {
            return;   // DB has been seeded
        }

        var members = new Member[]
        {
            new Member{FirstName="Carson",LastName="Alexander",DateOfBirth=DateTime.Parse("2005-09-01"), MembershipTypeId = 1},
            new Member{FirstName="Meredith",LastName="Alonso",DateOfBirth=DateTime.Parse("1995-09-01"), MembershipTypeId=1},
            new Member{FirstName="Arturo",LastName="Anand",DateOfBirth=DateTime.Parse("1986-09-01"), MembershipTypeId=3
        }

        };
        foreach (Member s in members)
        {
            context.Members.Add(s);
        }
        context.SaveChanges();

        var membershipTypes = new MembershipType[]
        {
            new MembershipType{Cost = 29.99 , PaymentType="Monthly" },
            new MembershipType{Cost= 229.99, PaymentType="Annually"},
            new MembershipType{Cost= 4.99, PaymentType="PAYG"}
        };
        foreach (MembershipType c in membershipTypes)
        {
            context.MembershipTypes.Add(c);
        }
        context.SaveChanges();
    }

这是我的POST请求创建操作方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,DateOfBirth,MembershipTypeId")] Member member)
{
    if (ModelState.IsValid)
    {
        _context.Add(member);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(member);
}

最后,下面是我的会员模型类,以及我的ViewModel类:

public class Member
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }


    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime DateOfBirth { get; set; }

    // foreign key for MembershipType 
    [ForeignKey("MembershipType")]
    public int MembershipTypeId { get; set; }

}


public class MemberViewModel
{
    public int MemberID { get; set; }
    public string FirstName { get; set; }

    public string LastName { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime DateOfBirth { get; set; }

    public string PaymentType { get; set; }

}

ID字段可能会被表自动递增,但我无法理解为什么这些值按照它们的方式编写(在引入ViewModel之后)

非常感谢任何帮助,

三江源

编辑 - 我不相信这个问题类似于Other question,与数据类型的缓存大小相似。

0 个答案:

没有答案