DbContext.SaveChanges()始终将id列的值赋给零

时间:2014-11-05 11:43:32

标签: c# dbcontext

我正在尝试使用流畅的api在c#中开发一个简单的应用程序。我想在我的Musteri表中插入一条记录(Musteri表示客户是土耳其语)。

我的musteri类在ModelRepository.cs中:

public class Musteri // It means Customer
{
    [Key]
    public int MusteriId  { get; set; }// It Means CustomerId
    public string MusteriAdi { get; set; } // It means CustomerName
}

以下代码位于form1.cs:

public class CustomerContext : DbContext
{
    public CustomerContext()
        : base("MySqlConnString") // I'm using MySql Database
    {
    }

    public DbSet<Musteri> MusteriTb { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

我正在使用以下代码插入记录我的Musteri(客户)表

CustomerContext context = new CustomerContext();
Musteri MusteriRow = new Musteri();
MusteriRow.MusteriId = Convert.ToInt32(TextBox1.Text);
MusteriRow.MusteriAdi = TexBox2.Text;
context.MusteriTb.Add(MusteriRow);

例如我在TextBox1中写“9”。我正在观看断点MusteriRow.MusteriId值。直到这里MusteriRow.MusteriId = 9。

context.SaveChanges()命令后,MusteriRow.MusteriId为0(零)。始终程序将MusteriRow.MusteriId的值分配给零。我怎么解决这个问题。请帮帮我。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我改变了我的模型类:

public class Musteri
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int MusteriId { get; set; }
    public string MusteriAdi { get; set; }
}

我从这个链接找到答案: Getting "Cannot insert the value NULL into column" when trying to save with .Add() method using DbContext . Please check my POCO's and save method