How can i using GetObjectByKey in mvc 5 using entity framword 6 - asp.net

I am using mvc 5 and ef 6 to build a project. I was simplify the retrieval code by adding some methods to partial class entity context. This is how i do it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.Entity.Core;
namespace MyShop.Models
{
public partial class DataEntities
{
public T GetById<T>(object id) where T : class
{
EntityKey key = CreateKey<T>(id);
return (T)GetObjectByKey(key);
}
private EntityKey CreateKey<T>(object id)
{
var type = typeof(T);
return new EntityKey("MyEntities." + "." + type.Name, "Id", id);
}
}
But it error at GetObjectByKey though i was add entityframwork 6.dll in my project, and i tried add some references but it don't work.
Can you help me fix the error.
Thanks you for read.
Phuong

Related

Pass data between controllers using method void

I need to pass values from one controllaro to a method from another controller.
or is there another way to pass data to an object so that object takes care of doing all the operations receiving values from other controllers
PRIMARY CONTROLLER
DateTime TimeLog = DateTime.Now;
LogController.Insert(TimeLog);
LOG CONTROLLER
using PROGRAM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PROGRAM.Controllers
{
public class LogController : Controller
{
Entities db = new Entities();
internal static void Insert(DateTime TimeLog)
{
LogModel log = new LogModel();
log.User = Session["User"].ToString();
log.TimeLog = TimeLog;
db.Log_Arqueo.Add(log);
db.SaveChanges();
}
}
}
ERROR
Severity Code Description Project File Line Status deleted
Error CS0120 An object reference is required for the non-static 'Controller.Session' field, method, or property PROGRAM\Controllers\LogController.cs 17 Active

Dapper.Contrib methods unavailable for IDbConnection object

I am trying to use Dapper.Contrib to extend the functionality of the IDbConnection interface with, amongst others, the .insert() method.
To do so, I have followed the somewhat brief and scattered documentation here and here. In short, I have used NuGet to add Dapper and Dapper.Contrib to my project, I have added using Dapper; and using Dapper.Contrib; at the top of my Repository class, and I am using System.Data.SqlClient.SqlConnection() to create an IDbConnection.
Still, my connection object does not have the extended methods available. For example, when trying to use the .insert() method, I get the message:
'IDbConnection' C# does not contain a definition for 'Insert' and no
extension method 'Insert' accepting a first argument of type could be
found (are you missing a using directive or an assembly reference?)
This is in an ASP.NET Core 2.0 project using Razor Pages.
For completeness sake, you can find the Repository class below.
Maybe interesting to note, is that the using lines for Dapper and Dapper.Contrib are grayed out...
Also, of course I have a (very minimalistic) Model Class for the TEST Entity, containing one parameter, TEST_COLUMN, annotated with [Key].
using Dapper.Contrib;
using Dapper;
using Microsoft.Extensions.Configuration;
using TestProject.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace TestProject.Repository
{
public class TEST_Repository
{
IConfiguration configuration;
public TEST_Repository(IConfiguration configuration)
{
this.configuration = configuration;
}
public void Insert()
{
using (var con = this.GetConnection())
{
con.Insert(new TEST { TEST_COLUMN = "test" });
}
}
public IDbConnection GetConnection()
{
return new SqlConnection(configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value);
}
}
}
The Insert method you are looking for lives inside of the Dapper.Contrib.Extensions namespace, as can be seen in the source, included for completeness:
namespace Dapper.Contrib.Extensions
{
...
public static long Insert<T>(this IDbConnection connection, ...)
...
}
Hence, in order to use the Extension methods, you should add the following line to your code:
using Dapper.Contrib.Extensions;

Code first - database isn't created

I'm trying to make a simple project in ASP.NET, 'code first'.
So I made a class EFDbContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCRubenWouters.Models
{
public class EFDbContext: DbContext
{
public EFDbContext() : base("name=rubenwoutersdbCF")
{
Database.SetInitializer<EFDbContext>(new EFDbInitializer());
}
public DbSet<Types> Types { get; set; }
}
}
And added a connectionstring in 'web.config'
<connectionStrings>
<add name="rubenwoutersdbCF" connectionString="Data Source=.\SQLSERVER2012;Initial Catalog=rubenwoutersdbCF;Integrated Security=True;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then I created a class "EFDbInitializer to add something to the database:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVCRubenWouters.Models
{
public class EFDbInitializer: DropCreateDatabaseAlways<EFDbContext>
{
protected override void Seed(EFDbContext context)
{
Types t1 = new Types()
{
PK_TypeNr = 1,
TypeKeuken = "Belgisch",
TypeZaak = "Restaurant",
Vegetarisch = false
};
context.Types.Add(t1);
context.SaveChanges();
}
}
}
When I run the project and go to the SQL server management studio (and refresh), no new database is there..
Am I doing something wrong here? :/
I would suggest you create your database in SQL server, build your tables, then fill them using your code.
The way that runs on my system is force the database in Application_Start()
try this:
Database.SetInitializer(new CreateDatabaseIfNotExists<EFDbContext>());
var context = new EFDbContext("Data Source=(local);Integrated Security=SSPI;Initial Catalog=myDB;");
context.Database.Initialize(true);
I think the seed method is never called, To ensure set a brakpoint
You can develop your custom intializer something like below link:
Seed in entity framework and then call it in Application_Start()
Database.SetInitializer<EFDbContext>(new EFDbInitializer());

MVC4 hosting views from other MVC project

I am attempting to figure out how to host MVC4 apps that were built under different solutions. There are many examples of doing this on SO and on the web using the RazorGenerator nuget package with Areas - it works very well. In my situation, I want to avoid using areas - every application my company develops will be in it's own MVC4 project (then collectively in the same solution).
I've integrated RazorGenerator into my apps, the code gen is working as expected. However, my host solution can not find the View in it's default locations. As an example, I have a Controller/View built in one app called MyAccount/Index.
Controller:
namespace Accounts.Controllers
{
public class MyAccountController : Controller
{
//
// GET: /MyAccount/
public ActionResult Index()
{
return View();
}
}
}
View (as generated from RazorGenerator):
namespace Accounts.Views.MyAccount
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.Security;
using System.Web.UI;
using System.Web.WebPages;
[System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "1.5.4.0")]
[System.Web.WebPages.PageVirtualPathAttribute("~/Views/MyAccount/Index.cshtml")]
public partial class Index : System.Web.Mvc.WebViewPage<dynamic>
{
public Index()
{
}
public override void Execute()
{
#line 1 "..\..\Views\MyAccount\Index.cshtml"
ViewBag.Title = "Index";
#line default
#line hidden
WriteLiteral("\r\n\r\n<h2>Index</h2>\r\n\r\nMy AccountController Index view.");
}
}
}
I know that by default, the ViewEngines are going to try to find this view in the default locations (Views and Shared), so I added my own ViewEngine to the Engines collection:
MyViewEngine.cs:
public class MyViewEngine : RazorViewEngine
{
private static string[] _viewLocations
= new string[]
{
"~/Accounts/Views/{1}/{0}.cshtml"
};
public MyViewEngine()
{
base.ViewLocationFormats = ViewLocationFormats.Union(_viewLocations).ToArray();
}
}
However, the view still isn't found:
The view 'Index' or its master was not found or no view engine supports the searched locations.
The following locations were searched:
~/Views/MyAccount/Index.cshtml
~/Views/Shared/Index.cshtml
~/Views/MyAccount/Index.aspx
~/Views/MyAccount/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/MyAccount/Index.vbhtml
~/Views/Shared/Index.vbhtml
~/Accounts/Views/MyAccount/Index.cshtml
Maybe I am misunderstanding how the view is located -I had thought it would have been found in Accounts/Views/MyAccount/. Any ideas what I might be doing wrong?
Thanks!
Found my issue - it was due to not having the RazorGeneratorMvcStart warmup code in place. It is generated automatically into the App_Start folder when you add the nuget package, however I erroneously removed it.

Populating a Telerik Grid using ViewModel (MVC3)

Ok, this is a really newbie question but I am stumped.
I am trying to use a ViewModel to get my data from an entity object and populate the telerik mvc grid.
At this point I am a bit confused and need your help.
I understand the error message but I am not sure how I need to fix this since I am really new to MVC.
----ERROR----
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?) ProjectRepository.cs 23 20 MvcMyAPP
I have this viewmodel:
--VIEWMODEL--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace mvcMyModel.ViewModels
{
public class ProjectViewModel
{
public IQueryable<mvcMyAPP.Models.ProjectRepository> ProjectList
{
get;
set;
}
}
}
--CONTROLLER--
namespace MvcMyAPP.Controllers
{
public class HomeController : Controller
{
// GET: /Home/
ProjectRepository Repository = new ProjectRepository();
public ActionResult Index()
{
ProjectViewModel objProjectViewModel = new ProjectViewModel();
objProjectViewModel.ProjectList = Repository.GetProjects();
return View(objProjectViewModel);
return View();
}
}
}
----REPOSITORY (MODEL)-----
namespace mvcMyAPP.Models
{
public class ProjectRepository
{
mvcMyAPP.Models.MYEntities MYDB = new MYEntities();
//Fetching data from table
public IQueryable<mvcMyAPP.ViewModels.ProjectViewModel> GetProjects()
{
var vProjects = (from tblProjects in MYDB.Projects
select tblProjects);
return vProjects;
}
}
---GRID---
#{Html.Telerik().Grid(Model.ProjectList)
.Name(
"Grid")
.Pageable()
.Sortable()
.Filterable()
.Groupable()
.Render();
}
You don't need the second return View() in the controller, but that isn't causing any problems.
You might try putting a cast on the return variable from your repository so it is returning the type specified in return:
// return vProjects;
// cast the return variable to return type
return (IQueryable<mvcMyAPP.ViewModels.ProjectViewModel>)vProjects;
I highly recommend Microsoft site for learning MVC, they have a great starting point for learning MVC.
http://www.asp.net/mvc

Resources