How to rewrite from Raw SQL to LINQ? - c#

I would like to replace my Raw SQL with LINQ. Here's my code:
MyController:
using MyProject.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MyProject.Controllers
{
public class MyController : ApiController
{
[HttpGet]
public List<User> UserData()
{
var selUserData = "SELECT * FROM mydb.User";
using (var ctx = new ApplicationDbContext())
{
var userData = ctx.Database.SqlQuery<User>(selUserData).ToList();
return userData;
}
}
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
}
Web.config:
<connectionStrings>
<add name="MyEntities" providerName="MySql.Data.MySqlClient" connectionString="server=127.0.0.1;port=3306;database=,mydb;uid=root;password=mypass" />
</connectionStrings>
ApplicationDBContext.cs:
using MySql.Data.Entity;
using System.Data.Entity;
namespace MyProject.Models
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext() : base(nameOrConnectionString: "MyEntities") { }
}
}
I've been searching the web for some days trying to find a solution, but no luck. Should my code look like something like var userData = ctx... which is just adding a few lines of LINQ syntax or am I doing it all wrong? I read about LINQ not being fully compatible with MySQL. What would my code look like if I were using MSSQL and what would look like if I were using MySQL?
EDIT:
UserDAL.cs:
public class UserDAL
{
public static List<User> UserData()
{
using (var ctx = new MyEntities())
{
var userData = ctx.Users.ToList();
return userData;
}
}
}
MyModel.Context.cs (autogenerated code):
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public partial class MyEntities : DbContext
{
public SloRideEntities()
: base("name=MyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Ride> Rides { get; set; }
}
User.cs (autogenerated code):
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Rides = new HashSet<Ride>();
}
public long Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Ride> Rides { get; set; }
}

You have to add a DbSet<User> to you context class
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext() : base(nameOrConnectionString: "MyEntities") { }
public virtual DbSet<Users> Users { get; set; }
}
Then you write
var userData = ctx.Users.ToList();

Assuming ApplicationDbContext is the class generated by Entity Framework T4 template based on your entity model (edmx file, database first approach) and you have included your mydb.User in the model - then your ApplicationDbContext class should have a property named User(s) which would be a collection of Users.
So you would have something like below
using (var ctx = new ApplicationDbContext())
{
return ctx.Users.ToList();
}

Related

How to acess a table in Code-First-Database?

For my Project I want to access the database but I have no clue because it is my first time programming with ASP.net mvc.
I have already read through a bunch of guides but to no avail.
Controller
This right here is my controller which gets a Code from a Machine (e.g.: 123456) but when I want to access the database through this option I get the No database provider has been configured for this DbContext. Error Message.
namespace Qualitätskontrolle.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult StartPage(string Code)
{
Debug.WriteLine(Code);
ApplicationDbContext dbContext = new ApplicationDbContext(.);
var dbErgebnisse = dbContext.Result.ToList();
for (int i = 0; i < dbErgebnisse.Count; i++)
{
Debug.WriteLine(dbErgebnisse[i]);
}
return View();
}
}
Context Class
I have read that the empty constructor should be removed but then I cannot access it in the Controller class.
namespace Qualitätskontrolle.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Bilder> Bilder { get; set; }
public DbSet<Prüfungen> Prüfungen { get; set; }
public DbSet<Ergebnis> Result { get; set; }
public DbSet<Typen> Typen { get; set; }
public DbSet<Typen_Pruefungen_Bilder> Typen_Pruefungen_Bilder { get; set; }
public DbSet<Einstellungen_KoordinatenSys> Einstellungen_KoordinatenSys { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Einstellungen_KoordinatenSys>()
.HasKey(c => new { c.ID, c.BildID });
modelBuilder.Entity<Ergebnis>()
.HasKey(c => new { c.BildID, c.TypenID, c.PruefungenID, c.BauTeilId });
modelBuilder.Entity<Typen_Pruefungen_Bilder>()
.HasKey(c => new { c.PruefungenID, c.TypenID });
}
}
}
Model
This is the model I need. I speficly need the BauTeilId for the Controller Class.
namespace Qualitätskontrolle.Models
{
public class Ergebnis
{
[Key]
public int TypenID { get; set; }
[Key]
public int PruefungenID { get; set; }
[Key]
public int BildID { get; set; }
[Key]
[StringLength(254)]
public string BauTeilId { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
public string XLabel { get; set; }
public int? X { get; set; }
public string YLabel { get; set; }
public int? Y { get; set; }
public string FehlerCode { get; set; }
public string FehlerName { get; set; }
public string FehlerGruppe1 { get; set; }
public string FehlerGruppe2 { get; set; }
public int Result { get; set; }
//1=IO 2=NIO
}
The result should be a list of BauTeilId which I can then check with the Code from the Controller.
If you need further information I will reply quickly.
I'm assume that it's not asp.net mvc core.
You should create separate class which implement DbContext e.g
public class ApplicationCustomDbContext : DbContext
{
public ApplicationCustomDbContext () : base("name=DefaultConnectionCustom")
{
}
// DbSet for your Entities
}
and in web.config you should specific connection string e.g.
<connectionStrings>
<add name="DefaultConnectionCustom" providerName="System.Data.SqlClient" connectionString="___" />
</connectionStrings>
There are multiple issues.
For ApplicationDbContext in .net core, you should register like below in Startup.cs
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
context.Configuration.GetConnectionString("ApplicationDbContextConnection")));
For connectionstring, you could configure in appsettings.json like
{
"ConnectionStrings": {
"ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CoreMVC2_2;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
For use, you could resolve from constructure like
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_mapper = mapper;
_context = context;
_userManager = userManager;
_userStore = userStore;
}
public async Task<IActionResult> Index()
{
var existingStudent = _context.Result.ToList();
return View();
}
}

Code First Entity Framework does not create database with tables

I have Couple of Models (Classes).
City.cs:
public class City
{
[ScaffoldColumn(false)]
public int CityID { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
Course.cs:
public class Course
{
[ScaffoldColumn(false)]
public int ID { get; set; }
public string Faculty { get; set; }
public int CityID { get; set; }
}
CourseDatabaseInitializer.cs:
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace CoursesApplication.Models
{
public class CourseDatabaseInitializer : DropCreateDatabaseAlways<CourseContext>
{
CourseContext _Context = new CourseContext();
protected override void Seed(CourseContext context)
{
GetCities().ForEach(c => context.Cities.Add(c));
}
private static List<City> GetCities()
{
var cities = new List<City> {
new City
{
CityID = 1,
Name = "Paris"
}
};
return cities;
}
public List<Course> GetCourses()
{
return (from c in _Context.Courses select c).ToList();
}
}
}
CourseContext.cs:
using System.Data.Entity;
namespace CoursesApplication.Models
{
public class CourseContext : DbContext
{
public CourseContext(): base("CoursesApplication")
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<City> Cities { get; set; }
}
}
and my Global.asax.cs file :
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Initialize the Courses database.
Database.SetInitializer(new CourseDatabaseInitializer());
}
, but when I run the application, everything is OK. After that in the solution explorer I create connection, but there is no Database with tables. This is my web.config with connection string:
<add name="CourseContext"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\courses.mdf;
Integrated Security=True"providerName="System.Data.SqlClient" />
Where can be the problem ?
I am using NET Framework 4.6.1 with Sql Express 2016.
This is ASP.NET WEB Forms project.
In CourseContext Try changing this
public CourseContext(): base("CoursesApplication")
{
}
to this
public CourseContext(): base("CourseContext")
{
}
or remove : base("CoursesApplication")

ASP.NET core with Entity Framework many-to-many not working

I have two models, and a model to connect the two.
Organization model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Verbonding.Models
{
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<OrganizationApplicationUser> OrganizationApplicationUsers { get; set; }
public Organization()
{
IsActive = true;
IsBlocked = false;
DateCreated = DateTime.Now;
DateUpdated = DateTime.Now;
}
public ApplicationUser AddUser(ApplicationUser user)
{
OrganizationApplicationUser ou = new OrganizationApplicationUser { ApplicationUser = user, Organization = this };
OrganizationApplicationUsers.Add(ou);
return user;
}
}
}
ApplicationUser model:
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Linq;
namespace Verbonding.Models
{
public class ApplicationUser : IdentityUser
{
public bool IsActive { get; set; }
public IQueryable<OrganizationApplicationUser> OrganizationApplicationUsers { get; set; }
public ApplicationUser():base()
{
IsActive = true;
IsBlocked = false;
DateJoined = DateTime.Now;
DateUpdated = DateTime.Now;
}
public IQueryable<Organization> GetOrganizations()
{
return OrganizationApplicationUsers.Select(x => x.Organization);
; }
}
}
DbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Verbonding.Models;
namespace Verbonding.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<OrganizationApplicationUser>().HasKey(x => new { x.OrganizationId, x.ApplicationUserId });
}
public DbSet<Country> Countries { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Organization> Organizations { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<OrganizationApplicationUser> OrganizationApplicationUsers { get; set; }
}
}
After some research I also added this code to the OnModelCreating method.
builder.Entity<OrganizationApplicationUser>()
.HasOne(ou => ou.Organization)
.WithMany(o => o.OrganizationApplicationUsers)
.HasForeignKey(ou => ou.Organization);
builder.Entity<OrganizationApplicationUser>()
.HasOne(ou => ou.ApplicationUser)
.WithMany(u => u.OrganizationApplicationUsers)
.HasForeignKey(ou => ou.ApplicationUserId);
Using the debugger I found out that OrganizationApplicationUsersremains null.
What could I do to fix this?
if you want to have what is called a many to many relationship between entities, you need to link the ApplicationUser to the Organization directly (under the hood, entity framework is gonna create the table between, but your class won't know about it.
Other than that, in the ApplicationUser, it should be an IColletion and not an IQueryable.

Dynamic DropDown list in MVC

I am very new to MVC and I am trying to make a CreateEmployee form in MVC. for now, all I am trying to achieve is to add the poulated dropdownlist for Departments to the form. the dropdownlist is populated from a database, and using Visual Studio, I connected to the DB and it created all the code file for the table. This is what the create form should look like. The form below is created using Angular js.
here is my Createform model.
public class CreateEmployee
{
public int Id { get; set; }
public string FullName { get; set; }
[Required]
public string Notes { get; set; }
//add the dropdown list of departments here,i not sure on what to do here
//do i create an instance of dbcontext here or AngtestDepartment
public bool PerkCar { get; set; }
public bool PerkStock { get; set; }
public bool PerkSixWeeks { get; set; }
public string PayrollType { get; set; }
}
public ActionResult CreateEmployee()
{
return View();
}
Here are the table codes that visual studio generated
Department Table
using System;
using System.Collections.Generic;
public partial class AngTestDepartment
{
public int id { get; set; }
public string Department { get; set; }
}
and the Department Table context
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class DepartmentDbContext : DbContext
{
public DepartmentDbContext()
: base("name=DepartmentDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<AngTestDepartment> AngTestDepartments { get; set; }
public System.Data.Entity.DbSet<AngularForms2.Models.CreateEmployee> CreateEmployees { get; set; }
}
You should query the DB in the controller and supply that to the View, e.g. via the model:
Add the following to your model:
public int Department { get; set; }
public IEnumerable<AngTestDepartment> Departments { get; set; }
and in your Action:
public ActionResult CreateEmployee()
{
using (var db = new DepartmentDbContext())
{
var model = new CreateEmployee();
model.Departments = db.AngTestDepartments.ToList();
return View(model);
}
}
then inside your view you can do something like:
#Html.DropDownListFor(m => m.Department,
Model.Departments.Select(d => new SelectListItem()
{
Value = d.id.ToString(),
Text = d.Department
}))

How to use DbContext without using Edmx in C#?

Can we use DbContext without adding EDMX in project for Data model here is sample code in which I am trying to save Instance class object with the help of ContextManager which is DbContext.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Linq;
using System.Text;
namespace DbContext_test
{
public class ContextManager : DbContext
{
public ContextManager(string connstring)
: base(connstring)
{
}
public override int SaveChanges()
{
//TODO: Write code before saving dataEntity object or fire some event to do so.
return base.SaveChanges();
}
}
public class Instances : EntityObject
{
public int ID { get; set; }
public string InstanceCode { get; set; }
public string InstanceName { get; set; }
}
public class InstanceManager
{
readonly string ConnectionString;
public InstanceManager(string connString)
{
ConnectionString = connString;
}
public void SaveInstance(int id, string instanceCode, string instanceName)
{
SaveInstanceInternal(new Instances { ID = id, InstanceCode = instanceCode, InstanceName = instanceName });
}
public void SaveInstance(Instances instance)
{
SaveInstanceInternal(instance);
}
private void SaveInstanceInternal(Instances instance)
{
var contextManager = new ContextManager(ConnectionString);
contextManager.Entry(instance);
contextManager.SaveChanges();
}
}
}
You can do it using the code first approach instead of the edmx approach.
http://www.entityframeworktutorial.net/code-first/what-is-code-first.aspx
follow this
1) create context class
public class SchoolPlusDBContext : DbContext
{
public SchoolPlusDBContext()
: base("name=SchoolPlusDBContext")
{
}
public DbSet<CategoryMaster> CategoryMaster { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
2) create class
public class CategoryMaster
{
[Key]
public long CategoryID { get; set; }
[Required]
public string CategoryName { get; set; }
[Required]
public string CategoryType { get; set; }
}
3) DA For query execution
public class CategoryDA
{
SchoolPlusDBContext dbContext = new SchoolPlusDBContext();
public List<CategoryMaster> GetAllCategory()
{
return dbContext.CategoryMaster.OrderByDescending(t => t.CategoryID).ToList();
}
public bool AddCategory(CategoryMaster master,string UserName)
{
try
{
master.CreatedBy = UserName;
master.CreatedOn = System.DateTime.Now;
dbContext.CategoryMaster.Add(master);
dbContext.SaveChanges();
}
catch
{
return false;
}
return true;
}
}
}

Categories

Resources