简体   繁体   中英

How to insert record into SQL Server using Entity Framework

I'm trying to insert a row in a table, but it's just updating the table. How to insert a new row in the table using Entity Framework?

public partial class Transformer_GSM
{
    public int id { get; set; }
    public double KW { get; set; }
}

Table columns

[id] [int] IDENTITY(1,1) PRIMARY KEY,
[KW] [float] NOT NULL

Table name: Transformer_GSM

In the context -

 public DbSet<Transformer_GSM> Transformer_GSM { get; set; }

Code:

public IHttpActionResult GSM(double KW)
{
        try
        {
            using (smartpondEntities DB = new smartpondEntities())
            {
                DATA.Transformer_GSM  t = new Transformer_GSM();
                t.KW = KW;
                DB.Transformer_GSM.Add(t);
                DB.SaveChanges();
            }

            var response = new
            {
                Success = true,
                Message = "Transformer data saved",
            };

            return Ok(response);
}

My guess would be that since the PK is an identity column you need to tell EF that, otherwise it thinks you are updating the record with ID = 0.

public partial class Transformer_GSM
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    public double KW { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM