Home > Mobile >  Transform SQL String to Entity Framework
Transform SQL String to Entity Framework

Time:08-24

I have a SQL statement in C# in a string variable:

string sqlString = "UPDATE \"MyTable\""
                     $" SET \"STATUS\" = {(int)StatusValue.Confirmed}"
                     $" WHERE \"ID\" = {MessageId}";

But now I need to transform it to Entity Framework, but unfortunately I do not know Entity Framework well enough. How do I do that?

CodePudding user response:

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

it would be like

 using (var db = new YourContextDB())
 {
  var result = db.TableName.SingleOrDefault(b => b.ColumnName == 
  parameter);
  if (result != null)
  {
    result.UpdatebleColumnName = "Some new value";
    db.SaveChanges();
  }
 }

check https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

CodePudding user response:

You don't need this string anymore. All you need is an instance of your DatabaseContext.

Your code would be similar to this one:

using var dbContext = new YourDbContext();
var message = dbContext.MyTable.FirstOrDefault(mt => mt.Id == MessageId);
message.Status = (int)StatusValue.Confirmed;
dbContext.SaveChanges();
  • Related