How to write a query to get data from entity datamodel? - asp.net-mvc-3

I want get data from one of my models. I am using Entity datamodel where I have some tables in my Entity model. I want to select data from EmployeeTable.
EmployeeTable
----------------
[EmpId]|[Empname]|[EmpAddress]
I want to select [EmpID] and [Empname] columns from table. I don't know how to do this in Entity Framework and I have to return the data as JSON.
I had tried this methods but I am not geting the data.
How can I write the linq query?
public ActionResult Index()
{
return View();
}
public JsonResult GetData()
{
int Param1;
Param1 = 1;
DataEntitiesModel data = new DataEntitiesModel();
//var procedure=db.Database.SqlQuery<DataEntitiesModel>("ResourceReports #EmployeeID",new SqlParameter("#EmployeeID", Param1) );
//var procedure = db.Database.SqlQuery<DataEntitiesModel>("Select * from EmployeeDetails");
return Json(procedure,JsonRequestBehavior.AllowGet);
}
Here's the model:
public class DataEntitiesModel
{
public Int16 EmpID{ get; set; }
[Required(ErrorMessage = "Title is required")]
public string EmpName{ get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
[Required(ErrorMessage = "Version is required")]
public string EmpAddress{ get; set; }
}
public class DataEntitiesDBContext : DbContext
{
public DbSet<DataEntitiesModel> ProjectReports { get; set; }
}

Here's a nice video from Pluralsight to get you started with Entity Framework. You generate a data context from your database and then query this context:
public ActionResult GetData()
{
using (var db = new DataEntitiesDBContext())
{
var result = db.ProjectReports.ToList().Select(e => new {
Id = e.EmpID,
Name = e.EmpName
});
return Json(result, JsonRequestBehavior.AllowGet);
}
}

Related

Url syntax with List property on complex type

Model:
[DataContract]
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[DataMember(Name ="id")]
public int Id{ get; set; }
[DataMember(Name = "fullName")]
public string FullName { get; set; }
}
[DataContract]
public class Department
{
public Department()
{
this.Employees = new List<Employee>();
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "employees")]
public List<Employee> Employees { get; set; }
}
Controller
public HttpResponseMessage Get([FromUri]Department model)
{
if (ModelState.IsValid)
{
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
Url : "http://localhost:2070/home/get/?id=1&name=IT&Employees=1,John"
I am trying to invoke above URL and the Model does not read the Employees. Other property like int,double,string,decimal are read by the Model.
Can anyone help me on what is the correct format in passing List thru Url.
Also, I dont want to decorate each of my class with modelbinders nor the parameter in my controller.
Tech : WebApi, .Net3.5
You need to specify the index of the list and property to bind with when using FromUri and list/array
Try it this way
http://localhost:2070/home/get/?id=1&name=IT&Employees[0].Id=1&Employees[0].Name=John

Foreign Class not populating after save in mvc 4

I am saving data using Ajax and at the same time I want it to display in list. below is Class of City
public class City
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int StateId { get; set; }
[ForeignKey("StateId")]
public virtual State state { get; set; }
}
my Post method is
[HttpPost]
public ActionResult EditCity(City obj)
{
try
{
aRepository.Save(obj);
var db = aRepository.Citys.FirstOrDefault(c => c.Id == obj.Id);
return PartialView("_iCity", db);
}
catch (Exception e)
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
Here db.state = null, it's not populating.
Should get you the state detail by :
or
var db = aRepository.Citys.FirstOrDefault(c => c.Id == obj.Id).Include(x=>x.StateId);
When you post the data for your server, your ViewModel should has StateId, if you are passing the Object state into it, by default Etity Framework will not persist.
I suppose you are using Lazy Loading , so you dont need to user Include to get the State entity

Having issue while trying to pass two model to the same view at a time in mvc 3

I'm trying to create my profile type page for my simple blog site. I have two simple model class like this:
public class UserInfoModel
{
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
public class NewPost
{
public string PostTitle { get; set; }
public string PostStory { get; set; }
}
I have created a joint model class of user & post to pass to view like this:
public class UserPostModel
{
public UserInfoModel User { get; set; }
public NewPost Post { get; set; }
}
The methods I wrote to retrieve the user & post info are like this:
public int GetUserID(string _UserName)
{
using (var context = new TourBlogEntities1())
{
var UserID = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return UserID.Single();
}
}
public UserInfo GetUserDetails(int _UserID)
{
using (var context = new TourBlogEntities1())
{
var UserDetails = (from s in context.UserInfoes
where s.UserID == _UserID
select s).Single();
return UserDetails;
}
}
public Post GetUserPosts(int _UserID)
{
using (var context = new TourBlogEntities1())
{
var entity = (from s in context.Posts
where s.UserID == _UserID
select s).Single();
return entity;
}
}
And finally I'm calling all my method from my controller action like this:
[Authorize]
public ActionResult MyProfile()
{
var Business = new Business();
var UserID=Business.GetUserID(User.Identity.Name);
var UserEntity=Business.GetUserDetails(UserID);
var PostEntity=Business.GetUserPosts(UserID);
var model = new UserPostModel();
model.User.UserName = UserEntity.UserName; // problem showing here
model.User.Email = UserEntity.Email;
model.Post.PostTitle = PostEntity.PostTitle;
model.Post.PostStory = PostEntity.PostStory;
return View("MyProfile",model);
}
A run time error showing like " object is not referenced to a object type or null object". I worked ok in a very similar way while passing single model. Whats I'm doing wrong here?
Modified your UserPostModel
public class UserPostModel
{
public UserPostModel()
{
User = new UserInfoModel();
Post = new Post();
}
public UserInfoModel User { get; set; }
public NewPost Post { get; set; }
}
NOTE: check each value before set to model it should not be null.

Binding ListBox with a model in MVC3

My model is
public class SiteConfig
{
public SiteConfig()
{
}
public int IdSiteConfig { get; set; }
public string Name { get; set; }
public byte[] SiteLogo { get; set; }
public string Brands { get; set; }
public string LinkColour { get; set; }
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
and
public class SiteBrand
{
public int Id { get; set; }
public int SiteId { get; set; }
public int BrandId { get; set; }
public Brand Brand { get; set; }
public SiteConfig SiteConfig { get; set; }
}
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
I am following Data Base first approach. Each SiteConfig record can contain one or more Brand. So Brand is saving to another table called SiteBrand.
SiteBrand contains the forign key reference to both SiteConfig(on IdSiteConfig) and Brand(BrandId).
When I am creating a SiteConfig I want to display all the available Brand as list box where user can select one or many record(may not select any brand).
But when I bind my view with the model how can I bind my list box to the list of brands and when view is posted how can I get the selected brands.
And I have to save the SiteConfig object to database with the selected Items. And this is my DB diagram.
This is my DAL which saves to db.
public SiteConfig Add(SiteConfig item)
{
var siteConfig = new Entities.SiteConfig
{
Name = item.Name,
LinkColour = item.LinkColour,
SiteBrands = (from config in item.SiteBrands
select new SiteBrand {BrandId = config.BrandId, SiteId = config.SiteId}).
ToList()
};
_dbContext.SiteConfigs.Add(siteConfig);
_dbContext.SaveChanges();
return item;
}
Can somebody advide how to bind the list box and get the selected items.
Thanks.
Add a new Property to your SiteConfig ViewModel of type string array. We will use this to get the Selected item from the Listbox when user posts this form.
public class SiteConfig
{
//Other properties here
public string[] SelectedBrands { get; set; } // new proeprty
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
In your GET action method, Get a list of SiteBrands and assign to the SiteBrands property of the SiteConfig ViewModel object
public ActionResult CreateSiteConfig()
{
var vm = new SiteConfig();
vm.SiteBrands = GetSiteBrands();
return View(vm);
}
For demo purposes, I just hard coded the method. When you implement this, you may get the Data From your Data Access layer.
public IList<SiteBrand> GetSiteBrands()
{
List<SiteBrand> brands = new List<SiteBrand>();
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 3, Name = "Nike" } });
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 4, Name = "Reebok" } });
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 5, Name = "Addidas" } });
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 6, Name = "LG" } });
return brands;
}
Now in your View, which is strongly typed to SiteConfig ViewModel,
#model SiteConfig
<h2>Create Site Config</h2>
#using (Html.BeginForm())
{
#Html.ListBoxFor(s => s.SelectedBrands,
new SelectList(Model.SiteBrands, "Brand.BrandId", "Brand.Name"))
<input type="submit" value="Create" />
}
Now when user posts this form, you will get the Selected Items value in the SelectedBrands property of the ViewModel
[HttpPost]
public ActionResult CreateSiteConfig(SiteConfig model)
{
if (ModelState.IsValid)
{
string[] items = model.SelectedBrands;
//check items now
//do your further things and follow PRG pattern as needed
}
model.SiteBrands = GetBrands();
return View(model);
}
You can have a "ViewModel" that has both the site and brand model in it. Then you can bind your view to that model. This would allow you to bind any part of the view to any part of any of the underlying models.
public class siteViewModel{
public SiteConfig x;
public Brand b; //Fill this with all the available brands
}
Of course you can include any other information your view might need (reduces the need of ViewBag as well).

AutoMapper problem with Dropdown

I´m started to work with AutoMapper today...
But I´m having some problem with Dropdown model...
What I have so far :
User Model
public class User : Entity
{
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual Role Role { get; set; }
}
Role Model
public class Role : Entity
{
public virtual string Name { get; set; }
}
UserUpdateViewModel
public class UserUpdateViewModel
{
public int Id{get;set;}
[Required(ErrorMessage = "Required.")]
public virtual string Name { get; set; }
[Required(ErrorMessage = "Required."), Email(ErrorMessage = "Email Invalid."), Remote("EmailExists", "User", ErrorMessage = "Email already in use.")]
public virtual string Email { get; set; }
[Required(ErrorMessage = "Required.")]
public virtual string Password { get; set; }
[Required(ErrorMessage = "Required")]
public virtual string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Required.")]
public int RoleId { get; set; }
public IList<Role> Roles { get; set; }
}
UserController
public ActionResult Update(int id=-1)
{
var _user = (_userRepository.Get(id));
if (_user == null)
return RedirectToAction("Index");
Mapper.CreateMap<User, UserUpdateViewModel>();
var viewModel = Mapper.Map<User, UserUpdateViewModel>(_user);
viewModel.Roles = _roleRepository.GetAll();
return View(viewModel);
}
[HttpPost, Transaction]
public ActionResult Update(UserViewModel user)
{
if (ModelState.IsValid)
{
user.Password = _userService.GetPasswordHash(user.Password);
Mapper.CreateMap<UserViewModel, User>();
var model = Mapper.Map<UserViewModel, User>(user); //model.Role = null
_userRepository.SaveOrUpdate(model); //ERROR, because model.Role = null
return Content("Ok");
}
return Content("Erro").
}
View Update
...
#Html.DropDownListFor(model => model.RoleId, new SelectList(Model.Roles, "Id", "Name"), "-- Select--", new { #class = "form radius" })
...
Some considerations:
1 - I´m returning Content() because is all Ajax enabled using HTML 5 PushState etc etc
2 - In my Update(POST one) method, my model returned by Autommapper has Role = null
Why my Role returned by Automapper is null?
Is that the right way to work with AutoMapper? Any tip?
Thanks
The map is failing because you are trying to map a single Role directly to a collection of Roles. And a collection of Roles back to a single Role. You cant directly map between these as they are different types.
If you wanted to map a Role to a List then you could use a custom value resolver.
Mapper.CreateMap<User , UserUpdateViewModel>()
.ForMember(dest => dest.Roles, opt => opt.ResolveUsing<RoleToCollectionResolver>())
Public class RoleToCollectionResolver: ValueResolver<User,IList<Role>>{
Protected override IList<Role> ResolveCore(User source){
var roleList = new List<Role>();
roleList.Add(source.Role);
Return roleList;
}
}

Resources