Convert EntityFramework to Raw SQL Queries in MVC - sql

I am trying to make a crud calendar in my .net, my question is, How do make the below entity framework codes to SQL queries?
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Thanks guys

You can run raw query in entity framework with dc.Database.ExecuteSqlCommand() command like below:
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
dc.Database.ExecuteSqlCommand(&#"
UPDATE Events
SET Subject = {e.Subject},
Start = {e.Start},
End = {End},
Description = {Description},
IsFullDay = {IsFullDay},
ThemeColor = {ThemeColor},
WHERE EventID = {e.EventID}
IF ##ROWCOUNT = 0
INSERT INTO Events (EventID, Subject, Start, End, Description, IsFullDay, ThemeColor)
VALUES ({e.EventID}, {e.Subject}, ...)
");
status = true;
}
return new JsonResult { Data = new { status = status }
};

Related

datediff with case statement in select query linq

select case statement in linq query.
Here is the query on sql:
select case when DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101)) = 0 then
Sum([Order].OrderSubtotal)
else
case when (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30) = 0 then Sum([Order].OrderSubtotal) else
Sum([Order].OrderSubtotal)/
(DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30)
end
end as 'Account Value' from [order] where And Account.ID = #Act_ID
I am trying the code here:
var query = _orderRepository.Table;
query = query.Where(o => o.AccountId == accountId);
In query i am getting my value.
After query statement what should i write??
how do i write for case statement using linq???
#Manoj, may be the below code helps you. This sample C# project may solve the problem you have.
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateDiffIssue
{
class Program
{
static void Main(string[] args)
{
// Preparing data
var data = new Order[] {
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 10:00"), OrderSubtotal = 100 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 12:00"), OrderSubtotal = 150 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 14:00"), OrderSubtotal = 150 }
};
// Selection
var selected = (from item in data
let accountData = data.Where(w => w.AccountID == 1)
let minDate = accountData.Min(m => m.CreatedOnUtc).Date
let maxDate = accountData.Where(w => w.AccountID == 1).Max(m => m.CreatedOnUtc).Date
let isSameDate = minDate == maxDate
let basedOn30Days = (maxDate - minDate).TotalDays / 30
let isInside30Days = (int)basedOn30Days == 0
let accountDataSum = accountData.Sum(s => s.OrderSubtotal)
select new
{
AccountValue = isSameDate ? accountDataSum :
isInside30Days ? accountDataSum :
accountDataSum / basedOn30Days
}).Distinct();
// Print each order
selected.ToList().ForEach(Console.WriteLine);
// Wait for key
Console.WriteLine("Please press key");
Console.ReadKey();
}
}
internal class Order
{
public int AccountID { get; set; }
public DateTime CreatedOnUtc { get; set; }
public int OrderSubtotal { get; set; }
}
}

How to rollback a transaction in EntityFramework?

I have two database tables named Courses and Transactions.Courses stores the details of a particular course and Transactions table stores the details of the transactions performed by a particular user.
My question is how can I make sure that entry in the CourseTable is saved only when transactions(add,edit,delete) regarding that particular course is saved into the TransactionTable
CourseTable is
TransactionTable is
Controller is
POST: /Course/Add
[HttpPost]
public ActionResult Add(CourseVM _mdlCourseVM)
{
string actionName=this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName=this.ControllerContext.RouteData.Values["controller"].ToString();
Course _course = new Course();
_course.Duration = _mdlCourseVM.Course.Duration;
_course.DurationMode = _mdlCourseVM.DurationModeId;
_course.InstalmentFee = _mdlCourseVM.Course.InstalmentFee;
_course.Name = _mdlCourseVM.Course.Name;
_course.SingleFee = _mdlCourseVM.Course.SingleFee;
_db.Courses.Add(_course);
int i = _db.SaveChanges();
if (i > 0)
{
Common _cmn=new Common();
//Add the transaction details
int k=_cmn.AddTransactions(actionName,controllerName,"");
//Want to commit changes to the coursetable here
if(k>0){
_db.commitTransaction()
}
//Want to rollback the committed transaction
else{
_db.rollbackTransaction();
}
}
}
I solved the above scenario by using System.Transactions.Hope anyone with same scenario find it useful.
using (TransactionScope _ts = new TransactionScope())
{
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
Course _course = new Course();
_course.Duration = _mdlCourseVM.Course.Duration;
_course.DurationMode = _mdlCourseVM.DurationModeId;
_course.InstalmentFee = _mdlCourseVM.Course.InstalmentFee;
_course.Name = _mdlCourseVM.Course.Name;
_course.SingleFee = _mdlCourseVM.Course.SingleFee;
_db.Courses.Add(_course);
int i = _db.SaveChanges();
if (i > 0)
{
Common _cmn = new Common();
int k = _cmn.AddTransactions(actionName, controllerName, "",Session["UserId"].ToString());
if (k > 0)
{
_ts.Complete();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { message = "error" }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { message = "error" }, JsonRequestBehavior.AllowGet);
}
}
}

Having error in updating my record in database my method as follows

What I have done wrong in this code ? (I am using MVC4 and EF)
As an example: Please clear this am fresher to use MVC4
EditResponse response = new EditResponse();
try
{
using (WeMatchContext db = new WeMatchContext())
{
B_MEMBER_REGISTER update = new B_MEMBER_REGISTER();
var output = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(output != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
You have to attach updated data with the db entity. please try this,
using (WeMatchContext db = new WeMatchContext())
{
var update = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(update != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
//below line of code is very important.
db.B_MEMBER_REGISTER.Attach(update);
db.Entry(update).State = EntityState.Modified;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
}
}

Error: Only primitive types or enumeration types are supported in this context

[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.

Why does this controller double the inserts when I try to archive the results of the Bing Search API?

I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.