简体   繁体   中英

Updating a database row from C#

I need help in updating a row on a database table and stuck in that. Anybody please help me how to achieve this?

I want to check whether the product already exists on my database and if yes, i need to check whether any of the fields is been changed since its been inserted from JSon, if thats the case, then I need to update the fields.

My model looks like this

namespace MySite.Models
{
    [TableName("Product")]
    [PrimaryKey("ProductId", autoIncrement = false)]
    [ExplicitColumns]
    public class Product
    {
        [Column("ProductId")]
        [PrimaryKeyColumn(AutoIncrement = false)]
        public Guid ProductId{ get; set; }        
        [Column("ProductName")]
        [NullSetting(NullSetting = NullSettings.Null)]
        public string ProductName { get; set; }
        [Column("ProductPrice")]
        [NullSetting(NullSetting = NullSettings.Null)]
        public string ProductPrice { get; set; }
        [Column("Category")]
        public string Category { get; set; }
    }
}

Upon user request for a productid, i check the database for whether the product exists in case not exsits, I insert from a json string retrieved from external url:

var myProduct = this.DatabaseContext.Database.Fetch<Product>("Select * from Product where ProductId = @0", productId);

JSon looks like:

{"productId":"4632fdeb-0b8e-471f-a44a-0b07b5444656","ProductName":"MyProduct ABC 01","ProductPrice":"1000","Category":"1"}

My insert looks like this:

Product productInfo = null;
productInfo = JsonConvert.DeserializeObject<Product>(jsonResponse);

if (!myProduct.Any())
{
    this.DatabaseContext.Database.Insert(productInfo);
}

I want to in the same way, update the product row from the same json string, in case it finds a record, how do I do that?

if (myProduct.Any())
{
    //I want to update the matching product row on the database, how do I do that?
}

You should take advantage of EF, if you are using it! Don't send custom queries, if those can be constructed for you by EF. So you should do something like below:

var productInfo = JsonConvert.DeserializeObject<Product>(jsonResponse);
var product = this.DatabaseContext.Products
  .FirstOrDefault(p => p.ProductId == productInfo.ProductId);

if (product == null) {
  // no product, insert
  this.DatabaseContext.Products.Add(productInfo);
}
else {
  // there is product, update, for example
  product.ProductPirce = productInfo.ProductPrice;
}

this.Databasecontext.SaveChanges();

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