Returning 'computed' field in Entity Framework - c#

I have this piece of code. My intention is to create field, which I can pass as textValue to SelectList object.
Here are my two entities:
public class Ski
{
public int ID { get; set; }
public int BrandID { get; set; }
public virtual Brand Brand { get; set; }
[NotMapped]
public string BrandName
{
get
{
return this.Brand.Name.ToString();
}
}
}
public enum BrandName
{
Blizzard, MCAD, ATOMIC
}
public class Brand
{
public int ID { get; set; }
public BrandName Name { get; set; }
}
And SelectList initialization
ViewBag.SkiID = new SelectList(db.Skis, "ID", "BrandName");
But such a solution does not seem to work.
How can such a thing be implemented then?
Error says that I have an associated DataReader.

Create this view model:
public class SkiViewModel
{
public string Text{ get; set; }
public int Value{ get; set; }
}
and change your code:
var result = db.Skis.Select(x => new SkiViewModel()
{
Text = x.BrandName.Name ,
Value = ID
});
ViewBag.Skis = new SelectList(result, "Value", "Text");
and in view:
#Html.DropDownList("Value", new SelectListItem(ViewBag.Skis , "Value", "Text"))

Related

Display specific field found by Id Entity Framework 6

I have thse two classes. The code works, I can add a Movie to an actor and viceversa.
However, on the frontend side I cannot display the Name of the entity I'm adding, I can only display the Id number.
If I use a DropDownListFor I can display the names of the actors but I can only save an actor through the Id field.
How do I make it so that I display only the actor name and still save it on the database?
public class Movie
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public int ActorId { get; set; }
[ForeignKey("ActorId")]
public ICollection<Actor> Actors { get; set; }
public int DirectorId { get; set; }
[ForeignKey("DirectorId")]
public Director Director { get; set; }
}
public class Actor
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int MovieId { get; set; }
[ForeignKey("MovieId")]
public ICollection<Movie> CreditedMovies { get; set; }
}
For your scenario you required view model with properties of DD as well.
MovieViewModel.cs
public class MovieViewModel
{
public Movie Movie{get;set;}
public List<SelectListItem> ActorDD {get;set;}
}
using above view model you will need to bind your DD like below
Controller
public ActionResult Home()
{
MovieViewModel model = new MovieViewModel();
model.ActorDD.Add(new SelectListItem { Text = "Actor1", Value = "1" });
model.ActorDD.Add(new SelectListItem { Text = "Actor2", Value = "2" });
model.ActorDD.Add(new SelectListItem { Text = "Actor3", Value = "3" });
return View(model);
}
Your view look like below.
Razor.cshtml
#Html.DropDownListFor(m=>m.Movie.ActorId, model.ActorDD)

MVC4: Retrieving a related list with Entity and casting it as List<> or IEnum<> for View Model

This a simple project where users can search for job postings by area of expertise. The relationship between Areas and Postings are Many-to-many. I seem to be able to get to the very last part of retrieving the correctly filtered list, but getting back into the view model keeps giving me different errors:
ViewModel:
public class AreaOfertasViewModel
{
public Oferta UnaOferta { get; set; }
public SelectList AreasTrabajo { get; set; }
public IEnumerable<Oferta> Ofertas { get; set; }
public int idArea { get; set; }
public AreaOfertasViewModel()
{
this.UnaOferta = UnaOferta;
this.Ofertas = new List<Oferta>();
cargarAreas();
}
private void cargarAreas()
{
PostulaOfertaContext db = new PostulaOfertaContext();
this.AreasTrabajo = new SelectList(db.Areas, "areaId", "Area");
}
}
}
Controller:
public ActionResult SearchXArea()
{
return View(new AreaOfertasViewModel());
}
[HttpPost]
public ActionResult SearchXArea(AreaOfertasViewModel aovm)
{
int id = aovm.idArea;
PostulaOfertaContext db = new PostulaOfertaContext();
var area = db.Areas.Where(c => c.areaId == id);
var ofertas = from c in db.Ofertas.Where(r => r.AreaTrabajo == area)
select c;
aovm.Ofertas = (IEnumerable<Oferta>)ofertas.ToList();
return View(aovm);
}
The line giving me issues is
aovm.Ofertas = (IEnumerable)ofertas.ToList();
I've tried List<> for Ofertas, and I've tried leaving it as .ToList() without casting, and casting it as different things, but it gives me errors about not being able to cast it, and "Cannot compare elements of type 'System.Collections.Generic.List`1'. Only primitive types, enumeration types and entity types are supported."
What's the solution here?
Model for AreaTrabajo:
public class AreaTrabajo
{
[Key]
public int areaId { get; set; }
public string Area { get; set; }
public virtual List<Oferta> oferta { get; set; }
}
Model for Oferta:
public class Oferta
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Titulo { get; set; }
[Required]
public DateTime Vencimiento { get; set; }
[Required]
public string Cargo { get; set; }
[Required]
public int HorarioComienzo { get; set; }
[Required]
public int HorarioFin { get; set; }
[Required]
public string DescripcionTareas { get; set; }
public int Remuneracion { get; set; }
[Required]
public int RangoEdadMin { get; set; }
[Required]
public int RangoEdadMax { get; set; }
public string TipoFormacion { get; set; }
public string Idiomas { get; set; }
public string Competencias { get; set; }
public string OtrosEstudios { get; set; }
public string Estado { get; set; }
public virtual List<AreaTrabajo> AreaTrabajo { get; set; }
public virtual TipoContrato TipoContrato { get; set; }
public virtual Empresa Empresa { get; set; }
public virtual List<Postulante> Postulantes { get; set; }
}
Answer
[HttpPost]
public ActionResult SearchXArea(AreaOfertasViewModel aovm)
{
int id = aovm.idArea;
PostulaOfertaContext db = new PostulaOfertaContext();
var area = db.Areas.Where(c => c.areaId == id).FirstOrDefault();
var ofertas = db.Ofertas.Where(s => s.AreaTrabajo.All(e => e.areaId == area.areaId)).ToList();
aovm.Ofertas = ofertas;
return View(aovm);
}
Sorry if my question wasn't clear enough. I needed to filter out from the many-to-many relationship, and this solved it.
You are getting an error because the actual sql is executed when you call tolist(). The error is in your sql because you are comparing AreaTrabago to a list.
[HttpPost]
public ActionResult SearchXArea(AreaOfertasViewModel aovm)
{
int id = aovm.idArea;
PostulaOfertaContext db = new PostulaOfertaContext();
var area = db.Areas.Where(c => c.areaId == id).FirstOrDefault();
var ofertas = db.Ofertas.Where(s => s.AreaTrabajo.All(e => e.areaId == area.areaId)).ToList();
aovm.Ofertas = ofertas;
return View(aovm);
}
Sorry if my question wasn't clear enough. I couldn't get the many-to-many relationship, and this solved the filtering problem perfectly.

Entity framework with Web Api returning object

Hi I am new to entity framework. I have following objects
public partial class lr
{
public lr()
{
this.lr_history = new HashSet<lr_history>();
this.people = new HashSet<person>();
}
public int _id { get; set; }
public string name { get; set; }
public string notes { get; set; }
public virtual ICollection<lr_history> lr_history { get; set; }
public virtual ICollection<person> people { get; set; }
In my Web Api controller I have following code
public class lrController : ApiController
{
private CTM db = new CTM();
// GET api/addL
public IEnumerable<lr> Getlr()
{
from a in DbContext.Activities
return db.lr.AsEnumerable();
}
In above Get method it returns lr but i want to return my own object like
lr.id
lr.name
lr_history.description
lrh_history.rate
Can anyone show me how to achieve this? Than
Create a new model:
class HistoryModel
{
public int Id { get; set; }
public string Name { get; set; }
public string HistoryDescription { get; set; }
public string HistoryRate { get; set; }
}
and return that:
public IEnumerable<HistoryModel> Getlr()
{
from a in DbContext.Activities
return db.lr.AsEnumerable()
.Select(x => new HistoryModel
{
Id = x.id,
Name = x.name,
HistoryDescription = x.history.description,
HistoryRate = x.history.rate
});
}
Instade of return db.lr.AsEnumerable();
try this
return db.lr.ToList();

filter DropDownList in mvc razor

I have Model in mvc razor. In this model(EcotourismAttractions) i have a list of Class ParameterList.
I want to have three DropDownList that filter item by EntityType.
First DropDownList show EntityType with value 1 second DropDownList EntityType with value 2 and third DropDownList shows EntityType with value 3.
For all DropDownList Value be Title of Parameters and Text be Id of Parameters.how can i do that???
public class EcotourismAttractions
{
public int Id{ get; set; }
public string LatinName{ get; set; }
public List<AreaManagement.Entities.Parameters> ParametersList{ get; set; }
}
public class Parameters {
public int Id { get; set; }
public byte EntityType { get; set; }
public int ParentId { get; set; }
public string Title { get; set; }
}
I'm not able to understand your question completely, always try to make your question look generic, if possible. Anyways best i can do is...
Create three IEnumerable for each dropdown.
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public IEnumerable<SelectListItem> EntityType1List { get; set; }
public IEnumerable<SelectListItem> EntityType2List { get; set; }
public IEnumerable<SelectListItem> EntityType3List { get; set; }
Initialize the list with desired values.
EntityType1List = new SelectList(ParametersList.Where(x=>x.EntityType == 1).ToList(), "Value","Text").ToList();
EntityType1List = new SelectList(ParametersList.Where(x=>x.EntityType == 2).ToList(), "Value","Text").ToList();
EntityType1List = new SelectList(ParametersList.Where(x=>x.EntityType == 3).ToList(), "Value","Text").ToList();
Render on view
#Html.DropDownListFor(x => x.Prop1 , new SelectList(Model.EntityType1List , "Value", "Text", Model.Prop1))
#Html.DropDownListFor(x => x.Prop2, new SelectList(Model.EntityType2List , "Value", "Text", Model.Prop2))
#Html.DropDownListFor(x => x.Prop3, new SelectList(Model.EntityType3List , "Value", "Text", Model.Prop3))

ViewModel adding custom class to another class

I created this viewmodel:
public class PlayerViewModel
{
PlayerRepository repo = new PlayerRepository();
public Player Player { get; set; }
public int SelectedUserID { get; set; }
public SelectList Users { get; set; }
public PlayerViewModel()
{
Player = new Player();
}
public PlayerViewModel(int id)
{
Player = repo.Retrieve(id);
Users = new SelectList(repo.GetUsers());
SelectedUserID = 0;
}
}
this I have in view:
#Html.DropDownListFor(x => x.SelectedUserID, Model.Users)
#Html.ValidationMessageFor(x => x.SelectedUserID)
and this in controller:
[Authorize]
public ActionResult Upravit(int id)
{
var playerview = new PlayerViewModel(id);
return View(playerview);
}
[Authorize,HttpPost]
public ActionResult Upravit(int id, PlayerViewModel playerView)
{
if (ModelState.IsValid)
{
playerView.Player.User = usRepo.GetUserById(playerView.SelectedUserID);
repo.Save(playerView.Player);
return RedirectToAction("Podrobnosti", new { id = playerView.Player.PlayerID });
}
return View(playerView);
}
Now I have problem that " The field SelectedUserID must be a number." and I have in dropdownlist UserName. I modified this many times, I tried with Dictionary and other ways but everyway has some problem. So I want just ask for best way to add custom class User to class Player.
Player class:
public class Player
{
// pokud použijeme virtual a vlastností tak nám EF rozšíří o další možnosti jako lazy loading a další
[Key]
public int PlayerID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public string PhotoUrl { get; set; }
public string Post { get; set; }
public virtual Team Team { get; set; }
public virtual User User { get; set; }
// public int UserID { get; set; }
//public virtual ICollection<Article> Articles { get; set; }
// Here could be next things as number, ...
}
Thanks
Use this constructor instead:
http://msdn.microsoft.com/en-us/library/dd505286.aspx
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
Something like this:
Users = new SelectList(repo.GetUsers(),"UserID", "UserName");

Categories

Resources