将EntityFramework转换为MVC中的原始SQL查询

时间:2018-05-14 05:40:44

标签: sql visual-studio entity-framework model-view-controller fullcalendar

我正在尝试在我的.net中制作一个crud日历,我的问题是,如何使下面的实体框架代码进行SQL查询?

[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

谢谢你们

1 个答案:

答案 0 :(得分:0)

您可以使用dc.Database.ExecuteSqlCommand()命令在实体框架中运行原始查询,如下所示:

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 } 
};