Entity Framework returns 0 items - c#

I`m using Entity Framework 6.1.3.
When i try to get values from database table it returns me 0 items but in database are 9 rows.
And Entity FrameWork invokes the OnModelCreating method.
I searched all internet but nothing found how to fix that.
My DbContext class
namespace TestTask.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class Entities : DbContext
{
public Entities()
: base("MenuItemsContainer")
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties()
.Where(p => p.Name == "Id")
.Configure(p => p.IsKey());
}
public virtual DbSet<DataMenuItemSet> DataMenuItemSet { get; set; }
public virtual DbSet<ItemsSet> ItemsSet { get; set; }
}
}
My DataMenuItemSet class
using System.ComponentModel.DataAnnotations;
namespace TestTask.Models
{
using System;
using System.Collections.Generic;
public partial class DataMenuItemSet
{
public DataMenuItemSet()
{
this.ItemsSet = new HashSet<ItemsSet>();
}
[Key]
public int Id { get; set; }
public bool IsRoot { get; set; }
public string Name { get; set; }
public Nullable<int> Parent { get; set; }
public virtual ICollection<ItemsSet> ItemsSet { get; set; }
}
}
All of this is generated with Entity Framework.
I need to get values from database.
Updated
I`ve solved the problem.
The point is that i have two projects in my solution. First is a site, that have the model from database, and second is simple ConsoleApplication, where i tried to test a database data. When i trying to connect to db via dbcontext from the other application its not working as described above. To make it work, I transfered a connection string from Web Site application, that have edmx model and dbcontext, to application, where i were testing this connection and data.
Here is how it works
Yellow - ConsoleApplication
Red - Web Site with model and dbcontext
Here is a model and Web.config
I transfered the connection string from Web.config to the App.cofig of ConsoleApplication, and the model.
ConsoleApplication with transfered model and connection string.
And after all that it works for me.
Thanks for help !!!

Here is the very common way to get data from db using entity framework and LINQ query.
using (var context = new Entities())
{
var L2EQuery = from item in context.DataMenuItemSet
where item.IsRoot == true
select item;
var result = L2EQuery.ToList()<DataMenuItemSet>;
}
Hope will be helpful.

Related

C# entity framework console. Why my returned data count is 0

Hello i have one problem. I cant get any data from my simple console app with Entity Framework. Database in on localdb and table is filled. all names are correct. if i change model class i get error so it means my entity framework connect with this db. Can u explain me why i cant get any datas?
Console.WriteLine(baseD.ConsoleEntities.Count()); returns 0 when there should be 3 rows.
class Program
{
static void Main(string[] args)
{
var baseD = new ConsoleDbContext();
Console.WriteLine(baseD.ConsoleEntities.Count());
Console.WriteLine("Done");
Console.ReadKey();
}
}
public class ConsoleDbContext : DbContext
{
public DbSet<Entity> ConsoleEntities { get; set; }
}
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
You need to specify the ConnString to the DbContext, try this:
public class ConsoleDbContext : DbContext
{
public ConsoleDbContext ()
: base("name=ConsoleDbContext")
{ }
public DbSet<Entity> ConsoleEntities { get; set; }
}
I GET IT!
So.. my model class named "Entity" is changed to "Entities" and ENTITIES is name of table. Why? because Entity framework adds 's' or 'es' to end of name cuz of "PluralizingTableNameConvention". Changes what repaired that test-learn project is changing name of table to Entities from entity or disable PluralizingTableNameConvention in Entity framework. Thanks for all answers!

How to create tables in codefirst approach

I am working on Login page creating in C# using Code First approach , in this I am getting lot of errors while trying to execute the code. I am a fresher and new to this .
Can you please review my code and help me what I missed in this ?
Rule are not creating and getting the multiple errors. Your help would help me to understand what went wrong in this.
My Class "Class1.cs"
public class Login
{
[Required]
public string username { get; set; }
[Required]
public string password{ get; set; }
}
}
public class LoginContext : DbContext
{
public LoginContext() : base("LoginDBConnectionString")
{
Database.SetInitializer<LoginContext>(new DropCreateDatabaseIfModelChanges<LoginContext>());
}
public DbSet<username> username { get; set; }
public DbSet<password> password { get; set; }
}
Context.cs
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.Entity;
using Jquery1.Models;
namespace Jquery1.Models
{
public class Logincontext: DbContext
{
public Logincontext () : base ("LoginDBConnectionString")
{
}
public DbSet<Login> Logins{ get; set; }
}
}
class program
{
static void Main(string[] args)
{
using (var ctx = new Logincontext())
{
ctx.Database.Create();
}`enter code here`
}
}
Hi Let me explain this using fluent api bear with me a little please,
Create Your DbContext First:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, YourApplication.Migrations.Configuration>("MyConnection"));
}
public DbSet<Users> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//here you can MAP Your Models/Entities, but i am going to show you something more interesting. so keep up.
modelBuilder.Configurations.Add(new UsersMap());
}
}
Create a Migration Folder in your app root And make Configuration class there(Why?! so that everytime you made a change migration of EF will update the Tables for you):
internal sealed class Configuration : DbMigrationsConfiguration<YourApplication.Infrastructure.Data.MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
//this feature on true can result in unwanted/unexpected dataloss
AutomaticMigrationDataLossAllowed = true;
ContextKey = "YourApplication.Infrastructure.Data.MyDbContext";
}
protected override void Seed(YourApplication.Infrastructure.Data.MyDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
Now Go on And Create Your POCO Classes. I try to write my codes very clean. That's why when for example i made a Model like below, i create an EntityBase for every Id:
public class EntityBase
{
public int Id { get; set; }
}
And Implement it to my Model :
public class User: EntityBase
{
public string Example1{ get; set; }
public string Example2{ get; set; }
public string Example3{ get; set; }
}
And For Mapping I Create another Class like below and use Fluent Api:
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
//declaring the table name
ToTable("TblUser");
//declaring primary key of the table
HasKey(x => x.Id);
//declaring a property from poco class is required
Property(x => x.Example1)
.IsRequired();
//etc
}
}
be aware if you are using fluent api, you Shouldn't use Data Annotations. Happy Coding.
Entity frame-work uses a concept of standards-or-else. If you want your items fairly standard, you don' have to provide a lot of information. If you want your tables to have different names, or your columns to be different than standard you'll have to provide extra information using either Attributes (the method you use) or fluent API.
Every class that should become a table should have an Primary key. The default is to give your class a property Id, or to give the property the name of your class followed by Id:
public class Login
{
public int Id {get; set;}
public string UserName {get; set;}
public string Password {get; set;}
}
public class MyDbContext : DbContext
{
public DbSet<Login> Logins {get; set;}
}
This should be enough to give you a table with the default name, which is the plural of your class name Logins. Each record in the table has three columns:
Id: the primary key
UserName: a string, which in this case may be null
PassWord: a string which may be null.
Your Requires attribute will ensure that your UserName and Property are not null, but they won't prevent them being empty. I'm not sure that's enough for you.
Instead of Id your are free to use LoginId as foreign key:
public int LoginId {get; set;}
You'll see both methods used. Both have their advantages. The use of Id shows you immediately which property is the primary key. LoginId could also be used as foreign key. The name LoginId alone is not enough to see whether it is a primary key or a foreign key.
The defaults are usually plurals for collections of items where the item is the singular form. Here you'll see Login as class, and Logins as a set of objects of this class.
The article that helped me a lot to get on track using Entity Framework was this entity framework tutorial
The tutorial tells you about how to use defaults, how to create one-to-many relations with foreign keys, many-to-many, various inheritance strategies, and what to do if you are not satisfied with a default model.

How to display table from SQL Server using ASP NET MVC5 without using Entity Framework?

I'm kind of new ASP.NET MVC 5, but I already have working code in a controller to access database and can perform queries and stored procedure. But after searching Google for answers, I'm still lost on how to be able to retrieve data from my database and display it in a table format without using Entity Framework due to reasons from manager.
In simple words, I just want to do something as simple as select * from table and be able to display the data in a table format.
Here's what I have tried:
I tried to create a model class via ADO.NET and got the following 2 classes:
namespace AsyncFileProcessor.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class AsyncFileProcessingStatus : DbContext
{
public AsyncFileProcessingStatus()
: base("name=AsyncFileProcessingStatus")
{
}
public virtual DbSet<AsyncFileProcessingQueue> AsyncFileProcessingQueues { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
namespace AsyncFileProcessor.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("AsyncFileProcessingQueue")]
public partial class AsyncFileProcessingQueue
{
public int ID { get; set; }
[Required]
[StringLength(256)]
public string Filename { get; set; }
[StringLength(256)]
public string Path { get; set; }
public int Status { get; set; }
public DateTime CreatedDate { get; set; }
public int CreatedById { get; set; }
public DateTime UpdatedDate { get; set; }
public int UpdatedById { get; set; }
}
}
Then I manually created a controller:
namespace AsyncFileProcessor.Controllers
{
public class FileProcessStatusController : Controller
{
// GET: FileProcessStatus
public ActionResult Index()
{
return View();
}
}
}
For view, I just want the table to be displayed in Index.cshtml
#{
ViewBag.Title = "DynamicFileUploader";
}
//Stuff here....
<div class="col-lg-6">
<h1 style="text-align:center;">Placeholder</h1>
// The table would go inside this section
</div>
I tried #model IEnumerable<AsyncFile.....> in Index.cshtml, but it doesn't recognize anything related to my model.
Tried a lot of solutions online, but my lack of knowledge about MVC5 fails me.
If someone can help me figure out how I can accomplish this and maybe explain the whole MVC5 workflow in simple terms, I would appreciate it.
I can do this easily in Django :(
You can use Dapper ORM developed by StackExchange.
It basically maps an object-oriented domain model to a traditional relational database. Otherwise, you will have to use ADO.Net.
For example,
public async Task<IList<AsyncFileProcessingQueue>> GetAsyncFileProcessingQueue()
{
IList<AsyncFileProcessingQueue> result;
using (IDbConnection conn = new SqlConnection(DataConnectionString))
{
conn.Open();
var entities = await conn.QueryAsync<AsyncFileProcessingQueue>
("SELECT * FROM YOUR_TABLE");
result = entities.ToList();
}
return result;
}
Dapper is lightweight and very fast. I use it, if I do not have control over Database or Database is not normalized.
If you want to write less SQL, but still have Dapper-like performance, you can use Tortuga Chain.
using Tortuga.Chain;
static SqlServerDataSource s_Data = new SqlServerDataSource(DataConnectionString);
public async Task<IList<AsyncFileProcessingQueue>> GetAsyncFileProcessingQueue()
{
return s_Data.From("YOUR_TABLE").ToCollection<AsyncFileProcessingQueue>().ExecuteAsync();
}
https://github.com/docevaad/Chain/wiki/A-Chain-comparison-to-Dapper

Console gets data but API call doesn't when using same method

I'm in the middle of creating a multi-tier application which includes the following layers
API
Business
DAL
-
Entities
All Layers have access to the Entities and also access to the layer that is beneath them in the list.
I also have a Console project.
My problem is that I make a call to the Business layer to get all data from a table, it works fine and retrieves two rows. However, I used the same method inside my API layer and it returns no rows - it also throws no errors and has left me stranded.
These are the classes/methods:
API:
public class CompaniesController : ApiController
{
CompaniesService _companiesService = new CompaniesService();
public IEnumerable<Company> GetAllCompanies()
{
return _companiesService.GetAllCompanies();
}
}
Business:
public class CompaniesService
{
public List<Company> GetAllCompanies()
{
var companyRepository = new CompanyRepository();
return companyRepository.GetAll();
}
}
DAL:
public class CompanyRepository
{
public List<Company> GetAll()
{
//create DBContext object
using (var context = new dbEntities())
{
var data = context.Company.ToList();
return data;
}
}
}
Entity:
[Table("Companies")]
public class Company
{
[Key]
[Column("ID")]
public int ID { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
public string Exchange { get; set; }
}
I am using Entity Framework 6 on Visual Studio 2013 and using a MySQL Database. Each layer is inside of a different project - just in case this is a reference based problem.
The problem was a simple fix, I simply didn't have the correct connection string inside of the API Project.

Add View - Cannot retrieve Metadata

I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.
Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities
The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.
There was an error running the selected code generator: 'Unable to
retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'
My controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class MoviesController : Controller
{
private MoviesEntities db = new MoviesEntities();
// GET: /Movies/
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ActionResult EmployeeInfo()
{
var query =
from m in db.Movies
join me in db.MovieEmployees
on m.ID equals me.movieID
join e in db.Employees
on me.employeeID equals e.ID
join r in db.Roles
on me.roleID equals r.ID
select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };
return View(query.Distinct().ToList());
}
}
}
My context
//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------
namespace WebApplication2.Entities
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using movieLayer;
using WebApplication2.Models;
public partial class MoviesEntities : DbContext
{
public MoviesEntities()
: base("name=MoviesEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Location> Locations { get; set; }
public virtual DbSet<Movie> Movies { get; set; }
public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<Show> Shows { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
}
}
Model of EmployeeInfo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication2.Models
{
public class EmployeeInfo
{
public EmployeeInfo() { }
public string Name { get; set; }
public string Role { get; set; }
public DateTime Birthday { get; set; }
}
}
What I did to solve this issue that I encountered when adding a scaffolded view by right clicking the controller action was to leave the "Data context class" field blank.
I'm not entirely sure as to why this works but I found this method from ASP.NET forums.
Make sure you rebuild your solution first. If you just added a new class, the scaffolding engine may not actually know about it, yet, if the project hasn't compiled.
If that doesn't work, close Visual Studio and restart. I have seen the scaffolding stuff just go wonky for no good reason in VS2012, and a restart will usually fix it.
The problem was the EmployeeInformation was just a "template" for the controller to dump it's data into from the query for the View.
EmployeeInformation was not actually an existing table, thus I had to make a model i.e. EmpleeInfoModels to hold the data, that was then passed to my custom View.
Method
public ActionResult EmployeeInformation()
{
var query =
from m in db.Movies
join me in db.MovieEmployees
on m.ID equals me.movieID
join e in db.Employees
on me.employeeID equals e.ID
join r in db.Roles
on me.roleID equals r.ID
select new EmployeeInfoModels() { Name = e.Name, RoleType = r.RoleType, Birthdate = e.Birthday, eID = e.ID };
return View(query.Distinct().ToList().Distinct());
}
Model
namespace WebApplication2.Models
{
public class EmployeeInfoModels
{
public int mID { get; set; }
public int eID { get; set; }
public string Name { get; set; }
public string RoleType { get; set; }
public DateTime Birthdate { get; set; }
}
}
And my View just brought in
#model IEnumerable<WebApplication2.Models.EmployeeInfoModels>
Adding one more tip: you may have this error if you have any configSource attributes in any of the elements in your web.config. I commented out all of the elements that contained a configSource attribute and then ran the scaffolding again and it worked like a charm. Once it was finished, I uncommented the elements in the web.config and I was all set.
Check your DataContextClass Option in Add View Pop winow and then correct the ConnectionString when adding your View from Controller
Refer Screenshot
.

Categories