How to load data from database in a ListBox? - c#

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I want to load data from my database in a ListBox, I did many searches but I don't find anything where Entity Framework is used.
In fact, I tried many solutions but always VS didn't accept the syntax.
This my model Class :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data.Entity;
namespace MvcApplication2.Models
{
public class Profile_Ga
{
[Key]
public string ID_Gamme { get; set; }
public string In_Ga { get; set; }
public string Out_Ga { get; set; }
public string Next_Gamme { get; set; }
public string Etat { get; set; }
}
}
I want to display ID_Gamme in a listBox?
In the view I did like this by it is not accepted.
<%: Html.ListBoxFor(model => model.ID_Gamme) %>
There is any solution?

ID_Gamme is a string (a singular value), so you can't make a list box for a singular value.
My guess is that you need a List<Profile_Ga> (or IEnumerable) to do the binding. Check your Entity classes, they should have a collection property for one of the classes you need.

Related

Guid[]:How to query and fetch details from Cosmos DB?

I am working with Azure CosmosDB. I am having below GetProgramsByStudentIDAsync method which needs to fetch all the programs associated to the studentID (Note that studentID is of type Guid).
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
public async Task<ProgramContainer> GetProgramsByStudentIDAsync(Guid[] studentIds)
{
var db = Client.GetDatabase(databaseId);
var programContainer = db.GetContainer(containerId);
using FeedIterator<ProgramContainer> feedIterator = programContainer.GetItemLinqQueryable<ProgramContainer>()
.Where(x => studentIds.Contains(x.StudentId)).ToFeedIterator(); //Giving me error at studentIds.Contains Please find the error details below:
CS1929: Guid[] does not contain a definition for 'Contains' and the best extension method overload requires a receiver of type
ProgramContainer class for reference:
public class ProgramContainer
{
public string ProgramName{ get; set; }
public string ProgramCode { get; set; }
public Guid StudentId { get; set; }
public bool IsActive { get; set; }
}
Please assist.Thanks in Advance!!!
Try explicitly casting to guid
using FeedIterator<ProgramContainer> feedIterator =
programContainer.GetItemLinqQueryable<ProgramContainer>()
.Where(x => studentIds.Contains((Guid)x.StudentId)).ToFeedIterator();

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

Entity Framework returns 0 items

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.

Visual Studio 2013 not recognizing reference to my new Model?

I'm working on an ASP.Net application. For one part of this, I have particular models stored in their own folder:
I have a reference to my Models/Default/ folder in one of my CustomControls: using Project.Models.Default; However, when I try to make a reference in my CustomControl YearsOfService to my default Model of Years_Of_Service, Visual Studio (2013) is not picking up either my Years_Of_Service or Years_Of_Service_Data model with my Models/Default/ folder:
Anyone have any ideas why this is happening?
EDIT:
Years_Of_Service.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PROJECT.Models
{
public class YearsOfService
{
public string Year { get; set; }
public decimal ServiceCredited { get; set; }
public decimal Salary { get; set; }
public string CoveredEmployer { get; set; }
}
}
Years_Of_Service_Data.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PROJECT.Models
{
public class YearsOfServiceData
{
public List<YearsOfService> YearsOfService { get; set; }
}
}
You currently have:
namespace PROJECT.Models
But this should also contain Default like this:
namespace PROJECT.Models.Default
So, it should end up like this:
namespace PROJECT.Models.Default
{
public class YearsOfServiceData
{
public List<YearsOfService> YearsOfService { get; set; }
}
}
Finally, you may want to keep your file names and class names the same otherwise it can get very confusing! So, stick with either Years_Of_Service_Data or YearsOfServiceData in both file and class name.
The classes contained in those files are just in the wrong namespace. Specify the correct one like this:
namespace XXXX.Models.Default
{
public class YearsOfService
{
//Snip
}
}
Alternatively, refer to them with their namespace as XXXX.Models.YearsOfService

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