I was trying to explore Code First today when I ran into a weird situation. I created 3 tables and entity framework created a 4th table for my many-to-many relationship. the code is as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pizza_test.models
{
public class Pizza
{
public int Id { get; set; }
public string Name { get; set; }
public float Price { get; set; }
public string Description { get; set; }
public int IngredientId { get; set; }
public virtual IList<Bottom> Bottoms { get; set; }
public virtual IList<Ingredient> Ingredients { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pizza_test.models
{
public class Bottom
{
public int Id { get; set; }
public string Name { get; set; }
public int Size { get; set; }
public virtual Pizza Pizzas { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pizza_test.models
{
public class Ingredient
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual Pizza Pizzas { get; set; }
}
}
The code of my dbcontext is as follows:
namespace pizza_test
{
using models;
using System;
using System.Data.Entity;
using System.Linq;
public class PizzaContext : DbContext
{
public PizzaContext()
: base("name=PizzaContext")
{
}
public DbSet<Pizza> Pizza { get; set; }
public DbSet<Ingredient> Ingredient { get; set; }
public DbSet<Bottom> Bottom { get; set; }
}
}
However when I try to query the database in my program.cs I am not allowed to call item.Ingredients.Name .
class Program
{
static void Main(string[] args)
{
var _context = new PizzaContext();
var firstPizza = _context.Pizza.Include(p => p.Ingredients).ToList();
foreach (var item in firstPizza)
{
Console.WriteLine(item.Ingredients.Name);
}
}
}
Which makes me kind of lost since i thought this was the power of ORMs. Did i forget something here? Also when i debug it in Visual Studio I can find all the related data of Ingredients including name, description and id. Thanks for any help provided.
Related
i am using entity framework in windowformapplication , when i call "db.Persons.Add()" it doesn't show refernce for Persons and gives the error :
Error : NBTSol.Models.ContactDbContext.Persons is inaccessible due to its protection level
even everything is public,
then why?
Person Model :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBTSol.Models
{
public class Person
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long PersonId { get; set; }
[Required(ErrorMessage = "First Name is Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is Required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email is Required")]
public string Email { get; set; }
[Required(ErrorMessage = "Gender is Required")]
public string Gender { get; set; }
[Required(ErrorMessage = "Address is Required")]
public string Address { get; set; }
[Required(ErrorMessage = "City is Required")]
public string City { get; set; }
[Required(ErrorMessage = "State is Required")]
public string State { get; set; }
[Required(ErrorMessage = "PostalCode is Required")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is Required")]
public string Country { get; set; }
[Required(ErrorMessage = "Contact Number is Required")]
public string ContactNumber { get; set; }
[Required(ErrorMessage = "CNIC is Required")]
public string CNIC { get; set; }
public string OrganizationName { get; set; }
public string Designation { get; set; }
public string Salary { get; set; }
public string Description { get; set; }
public Nullable<bool> IsClient { get; set; }
public DateTime EntryDateTime { get; set; }
public Nullable<bool> IsDeleted { get; set; }
}
}
My Context Class :
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBTSol.Models
{
public class ContactDbContext :DbContext
{
public ContactDbContext() : base( "name=DefaultConnection") { }
DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using Fluent API here
base.OnModelCreating(modelBuilder);
}
}
}
main form :[here is the error when i try to call "db.Persons.Add()"]
using NBTSol.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NBTSol
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
ContactDbContext db = new ContactDbContext();
Person person = new Person();
db.Persons.Add(person);
}
}
}
Make Person property public in your db context as following and it will work.
public DbSet<Person> Persons { get; set; }
Replace your ContactDbContext class with following code:
public class ContactDbContext: DbContext {
public ContactDbContext(): base("name=DefaultConnection") {}
public DbSet < Person > Persons {
get;
set;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
//Configure domain classes using Fluent API here
//Configure table name
modelBuilder.Entity<Persons>()
.ToTable("Persons ");
base.OnModelCreating(modelBuilder);
}
}
Why am I receiving errors when using views and controllers created via scaffolding with MVC 5 / EF 6 (inheritance) derived classes?
My background: I am a previous Powerbuilder (client/server programmer) that is endeavoring to learn web-based programming.
I chose ASP.NET and purchased an MSDN license to use Visual Studio 2013 and have been learning by books, online training and plain old hacking on the computer.
The best test is to create some sample application and so here I am. I am learning the MVC and Code First EF because there is so much good info and samples to be had.
However, I am stuck on my inheritance example.
I have 3 classes: AircrewMember derived from Airman derived from Person. They compile without error.
I have a class DbInitializer so "Code First" will create the database. I actually use SQL scripts to load my test data.
I have a class StanEvalDb for the database context info.
I have included pertinent information from web.config.
The problem:
When I use scaffolding to create a controller and views based off of the Airman class (derived from Person), the result returns with errors.
Airman airman = db.People.Find(id);
Error 1
Cannot implicitly convert type 'SEMX1.Entities.Person' to 'SEMX1.Entities.Airman'. An explicit conversion exists (are you missing a cast?)
D:\Projects\VC2013\2015\06-Jun\SEMX1\SEMX1.Web\Controllers\AirmenController.cs 31 29 SEMX1.Web
I think I understand the Table per Hierarchy (TPH) and that physically only one table (People) is created to house all "3" tables.
I am at a loss... I have googled and read many articles but I have no idea how to proceed. Has anyone seen this or tried this?
I assume I am overlooking something simple but I am out of ideas. Any help would be appreciated!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEMX1.Entities
{
public class Person
{
public virtual int PersonId { get; set; }
[DisplayName("First Name* ")]
[StringLength(40)]
[Required(ErrorMessage = "The First Name field is required.")]
public virtual string PersonFirstName { get; set; }
[DisplayName("Middle Initial ")]
[StringLength(2)]
public virtual string PersonMidInit { get; set; }
[DisplayName("Last Name* ")]
[StringLength(50)]
[Required(ErrorMessage = "The Last Name field is required.")]
public virtual string PersonLastName { get; set; }
[DisplayName("SSN* ")]
[StringLength(11)]
[Required(ErrorMessage = "The SSN field is required.")]
public virtual string PersonSSN { get; set; }
[DisplayName("DOB* ")]
[Required(ErrorMessage = "The DOB field is required.")]
public virtual DateTime? PersonDOB { get; set; }
public virtual int CivilRankId { get; set; }
//public virtual int LifeEventId { get; set; }
public virtual ICollection<LifeEvent> LifeEvents { get; set; }
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEMX1.Entities
{
public class Airman : Person
{
public virtual int MilitaryRankId { get; set; }
public virtual int MilitaryUnitId { get; set; }
public virtual int AfscId { get; set; }
public virtual ICollection<CareerEvent> CareerEvents { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEMX1.Entities
{
public class AircrewMember : Airman
{
public virtual int AviationTypeId { get; set; }
public virtual int AirMissionId { get; set; }
public virtual int AircraftId { get; set; }
public virtual int CrewPositionId { get; set; }
public virtual int ExperienceRatingId { get; set; }
public virtual int AirmanshipId { get; set; }
public virtual int TacticalDayRatingId { get; set; }
public virtual int TacticalNightRatingId { get; set; }
public virtual ICollection<AircrewEvent> AircrewEvents { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using SEMX1.Entities;
using System.IO;
namespace SEMX1.Web.DataContexts
{
public class DbInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<StanEvalDb>
{
protected override void Seed(StanEvalDb context)
{
base.Seed(context);
// using SQL scripts to load database with test data
// easier way to get around identity key field problems
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using SEMX1.Entities;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace SEMX1.Web.DataContexts
{
public class StanEvalDb : DbContext
{
public StanEvalDb() : base("StanEvalContext")
{
Database.SetInitializer<StanEvalDb>(new DbInitializer());
}
public DbSet<Person> People { get; set; }
public DbSet<LifeEvent> LifeEvents { get; set; }
public DbSet<CivilRank> CivilRanks { get; set; }
public DbSet<MilitaryRank> MilitaryRanks { get; set; }
public DbSet<MilitaryUnit> MilitaryUnits { get; set; }
public DbSet<MilUnitType> MilUnitTypes { get; set; }
public DbSet<AFSC> AFSCList { get; set; }
public DbSet<CareerEvent> CareerEvents { get; set; }
public DbSet<Airman> Airmen { get; set; }
public DbSet<AviationType> AviationTypes { get; set; }
public DbSet<AirMission> AirMissions { get; set; }
public DbSet<Aircraft> AircraftList { get; set; }
public DbSet<CrewPosition> CrewPositions { get; set; }
public DbSet<ExperienceRating> ExperienceRatings { get; set; }
public DbSet<Airmanship> AirmanshipList { get; set; }
public DbSet<TacticalDayRating> TacticalDayRatings { get; set; }
public DbSet<TacticalNightRating> TacticalNightRatings { get; set; }
public DbSet<AircrewEvent> AircrewEvents { get; set; }
public DbSet<AircrewMember> Aircrew { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Entity<Person>()
// .HasMany(p => p.LifeEvents).WithMany(l => l.People)
// .Map(t => t.MapLeftKey("PersonID")
// .MapRightKey("LifeEventID")
// .ToTable("LifeEventPersons"));
//modelBuilder.Entity<Airman>()
// .HasMany(a => a.CareerEvents).WithMany(c => c.Airmen)
// .Map(t => t.MapLeftKey("PersonID")
// .MapRightKey("CareerEventID")
// .ToTable("CareerEventAirmen"));
//modelBuilder.Entity<AircrewMember>()
// .HasMany(a => a.AircrewEvents).WithMany(c => c.Aircrew)
// .Map(t => t.MapLeftKey("PersonID")
// .MapRightKey("AircrewEventID")
// .ToTable("AircrewEventAircrew"));
}
}
}
Web.config (Pertinent Information)
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<connectionStrings>
<add name="StanEvalContext"
connectionString="Data Source=REDCARBOSS2-LAP\RCB2SRV2012;Initial Catalog=DB_25213_SEMX1;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
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 SEMX1.Entities;
using SEMX1.Web.DataContexts;
namespace SEMX1.Web.Controllers
{
public class AirmenController : Controller
{
private StanEvalDb db = new StanEvalDb();
// GET: Airmen
public ActionResult Index()
{
return View(db.People.ToList());
}
// GET: Airmen/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Airman airman = db.People.Find(id);
if (airman == null)
{
return HttpNotFound();
}
return View(airman);
}
// GET: Airmen/Create
public ActionResult Create()
{
return View();
}
// POST: Airmen/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonId,PersonFirstName,PersonMidInit,PersonLastName,PersonSSN,PersonDOB,CivilRankId,MilitaryRankId,MilitaryUnitId,AfscId")] Airman airman)
{
if (ModelState.IsValid)
{
db.People.Add(airman);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(airman);
}
// GET: Airmen/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Airman airman = db.People.Find(id);
if (airman == null)
{
return HttpNotFound();
}
return View(airman);
}
// POST: Airmen/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PersonId,PersonFirstName,PersonMidInit,PersonLastName,PersonSSN,PersonDOB,CivilRankId,MilitaryRankId,MilitaryUnitId,AfscId")] Airman airman)
{
if (ModelState.IsValid)
{
db.Entry(airman).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(airman);
}
// GET: Airmen/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Airman airman = db.People.Find(id);
if (airman == null)
{
return HttpNotFound();
}
return View(airman);
}
// POST: Airmen/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Airman airman = db.People.Find(id);
db.People.Remove(airman);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
The error says that it cannot implicitly cast and is asking you to explicitly cast. Try replacing this:
Airman airman = db.People.Find(id);
With:
Airman airman = (Airman)db.People.Find(id);
Category model is self referencing
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
public int? ParentID { get; set; }
public Category Cat { get; set; }
public ICollection<Category> Categories { get; set; }
public ICollection<BusinessDetail> BDetails { get; set; }
}
and BusinessDetail is like
public class BusinessDetail
{
[Key]
public int ID { get; set; }
[Required]
[Display(Name="Business Name")]
public string BusinessName { get; set; }
public string Address { get; set; }
[Display(Name="Contact")]
public string contactDetail { get; set; }
// public int CategoryID { get; set; }
// public Category Category { get; set; }
public int ? LocationID { get; set; }
public Location Location { get; set; }
[Display(Name="Website Address")]
public string Website_Address { get; set; }
[Display(Name="Is Verified")]
public bool Is_verified { get; set; }
[Required]
[Display(Name="Added By")]
public string Added_By { get; set; }
[Required]
[Display(Name="Added Date")]
[DataType(DataType.DateTime)]
public DateTime Added_Date { get; set; }
[Display(Name="Is Featured")]
public bool Is_Featured { get; set; }
public string Latitude { get; set; }
public string VerifiedBy { get; set; }
public string Longitude { get; set; }
public ICollection<Category> Categories { get; set; }
}
When creating a many-to-many relationship using Fluent API
modelBuilder.Entity<BusinessDetail>()
.HasMany(c => c.Categories).WithMany(i => i.BDetails)
.Map(t => t.MapLeftKey("ID")
.MapRightKey("CategoryID")
.ToTable("BusinessCategories"));
I get this error
There are no primary or candidate keys in the referenced table
'dbo.BusinessDetails' that match the referencing column list in the
foreign key 'FK_dbo.BusinessCategories_dbo.BusinessDetails_ID'.
I need help on this error.
I will try to work out your exact example, but the code below works without any configuration:
EDIT:
I added in the code from OnModelCreating and changed the property names to those in your exampe, but it all keeps working. You do realize though, that the ParentId property is not seen as the foreign key for a parent Category, but that EF will create a Cat_CategoryId foreign key for you?
I advise to start from scratch using my code and work step by step towards the existing code.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.Entity;
public class CategoryContext : DbContext
{
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Fill in later.
}
}
public class Category
{
public Category()
{
Children = new List<Category>();
Details = new List<BussinesDetail>();
}
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
public virtual ICollection<BussinesDetail> Details { get; set; }
}
public class BussinesDetail
{
public int Id { get; set; }
public string BussinesName { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
static class Module1
{
public static void Main()
{
using (context = new CategoryContext()) {
var newCat = context.Categories.Add(new Category { Name = "CatOne" });
context.SaveChanges();
newCat = context.Categories.Single;
Console.WriteLine(newCat.Name);
Console.ReadLine();
}
}
}
I'm using a model first approach. So, I got a generated class
namespace XXX.GlobalDatabaseModel
{
using System;
using System.Collections.Generic;
public partial class LocalizedFoodGroup
{
public int FoodGroupId { get; set; }
public string Culture { get; set; }
public string LocalizedName { get; set; }
public virtual FoodGroup FoodGroup { get; set; }
}
}
and, in another file in the same solution I want to add an index to it:
namespace XITASO.GlobalDatabaseModel
{
[MetadataType(typeof(LocalNameLocalizedFoodGroup))]
public partial class LocalizedFoodGroup
{
}
public class LocalNameLocalizedFoodGroup
{
[Index("UX_LocalizedFoodGroup",IsUnique = true)]
public string Culture { get; set; }
}
}
Only, when I click "generate database from model" and look at the sql file, no index shows up.
Does anybody know what I'm doing wrong?
Lots of Greetings!
Volker
I have the following relationship between the entities.
Company 1 ---* Appointments *---1 Employee
I have the .net asp membership in a separate database. Whenever a user is created it can be assigned to companies, employees, or administrators roles.
in the Index action of my Company Controller, I check the logged in user's role. Based on the role, I make different linq query. For example, administrators can get list of all companies, companies can get list of company which has a username property (string) same as the User.Identity.Name. For both of administrators and companies role, it is working fine.
For the employees role, I want to load all the companies that are related to the current employee. I am having hard time to compose a linq query that does this job.
i tried
var companies = db.Companies.Include(c => c.Appointments.Select(a=>a.Employee).Where(e=>e.Username.ToLower() == this.User.Identity.Name.ToLower())).ToList();
to which i get this error
"The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path"
Here are the source code,
CompanyController
[Authorize]
public class CompanyController : Controller
{
private MyDBContext db = new MyDBContext();
//
// GET: /Company/
public ViewResult Index()
{
var viewModel = new CompanyIndexViewModel();
if (Roles.IsUserInRole("administrators")) {
viewModel = new CompanyIndexViewModel { Companies = db.Companies.ToList() };
}
else if (Roles.IsUserInRole("companies")) {
viewModel = new CompanyIndexViewModel { Companies = db.Companies.Where(c => c.Username.ToLower().Equals(this.User.Identity.Name.ToLower())).ToList() };
}
else if (Roles.IsUserInRole("employees")) {
var companies = db.Companies.Include(c => c.Appointments.Select(a=>a.Employee).Where(e=>e.Username.ToLower() == this.User.Identity.Name.ToLower())).ToList();
viewModel = new CompanyIndexViewModel { Companies = companies.ToList() };
}
return View(viewModel);
}
...
Models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TorontoWorkforce.Models
{
public class Company
{
public int CompanyId { get; set; }
[Required]
public string Username { get; set; }
[Display(Name="Company Name")]
[Required]
public string Name { get; set; }
[UIHint("PhoneNumber")]
public string Phone { get; set; }
[DataType(DataType.Url)]
public string Website { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public AddressInfo AddressInfo { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
public virtual ICollection<Appointment> Appointments { get; set; }
public Company(){
this.AddressInfo = new AddressInfo();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TorontoWorkforce.Models
{
public class Appointment
{
public int AppointmentId { get; set; }
[Required]
[UIHint("DateTime")]
[Display(Name="Appointment Date")]
public DateTime? DateOfAppointment { get; set; }
[Required]
public int CompanyId { get; set; }
[Required]
public int EmployeeId { get; set; }
[Required]
[UIHint("MultilineText")]
[Display(Name = "Appointment Summary")]
public string Description { get; set; }
[Display(Name="Allocated No of Hours")]
public decimal NoOfHoursWorked { get; set; }
public virtual Company Company { get; set; }
public virtual Employee Employee { get; set; }
public virtual ICollection<AppointmentLine> AppointmentLines { get; set; }
public Appointment() {
//this.AppointmentLines = new List<AppointmentLine>();
this.DateOfAppointment = DateTime.Now;
}
[NotMapped]
[Display(Name="Actual No of Hours")]
public decimal ActualHoursWorked {
get
{
decimal total = 0;
foreach (var jobline in this.AppointmentLines)
{
total = total + jobline.TimeSpent;
}
return total;
}
}
}
public class AppointmentLine
{
public int AppointmentLineId { get; set; }
[UIHint("MultilineText")]
[Required]
public string Description { get; set; }
[Display(Name="Time Spent")]
[DataType(DataType.Duration)]
public decimal TimeSpent { get; set; }
public int AppointmentId { get; set; }
public virtual Appointment Appointment { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TorontoWorkforce.Models
{
public class Employee: TorontoWorkforce.Models.Person
{
public int EmployeeId { get; set; }
[Required]
public string Username { get; set; }
[Display(Name="Date Hired")]
public DateTime? DateHired { get; set; }
[Required]
public string Position { get; set; }
public virtual ICollection<Appointment> Appointments { get; set; }
public Employee() {
this.DateHired = DateTime.Now;
}
}
}
If you want to get companies which have appointment with selected employee you don't need to use Include. Include is for instructing EF to load all appointments related to the company (and it doesn't support filtering). Try this:
string userName = this.User.Identity.Name.ToLower();
var companies = db.Companies.Where(c => c.Appointments.Any(a =>
a.Employee.Username.ToLower() == userName)).ToList();
I think you just have an end parentheses in the wrong place. You need one more after "a => a.Employee" and one less after "this.User.Identity.Name.ToLower()));"
Try this code:
var companies = db.Companies.Include(c => c.Appointments.Select(a=>a.Employee)).Where(e=>e.Username.ToLower() == this.User.Identity.Name.ToLower()).ToList();
Edit:
You should also be able to use the standard string include method:
var companies = db.Companies.Include("Appointments.Employee").Where(e=>e.Username.ToLower() == this.User.Identity.Name.ToLower()).ToList();