I am using a objectDataSource to populate a gridview. I have 2 simple classes :
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public Department Department { get; set; }
}
and
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public List<Employee> Employees { get; set; }
}
I also have
public class EmployeeDBContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
now in my EmployeeRepository class i have
public List<Department> GetDepartments()
{
EmployeeDBContext employeeDBContext = new EmployeeDBContext();
return employeeDBContext.Departments.Include("Employees").ToList();
}
Even though I have added .Include("Employees"), the employees are missing in gridview. what am I doing wrong here?
First of all, you will need to have a foreign key (DepartmentId) inside Employee class. I do not know how the video got away with that.
public class Employee
{
public int Id { get; set; }
public int DepartmentId { get; set; } <=====
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public virtual Department Department { get; set; }
^^^^^^^
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
^^^^^^^^^^^^^^^^^^
}
public partial class EmployeeDBContext : DbContext
{
public virtual DbSet<Employee> Employee { get; set; }
public virtual DbSet<Department> Department { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Optional, but good practice to have the mapping here.
modelBuilder.Entity<Department>()
.HasMany(e => e.Employee)
.WithRequired(e => e.Department)
.HasForeignKey(e => e.DepartmentId);
}
}
- OR -
Add DepartmentId property and [ForeignKey] data annotation to Department.
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public int DepartmentId { get; set; } <===
// Optional, but good practice to have this data annotation attribute.
[ForeignKey("DepartmentId")] <===
public Department Department { get; set; }
}
FYI: You want to use virtual, in case someone wants to use lazy loading in the future.
have you tried something like this
return employeeDBContext.Departments.Include(x =>x.Employees ).ToList(); ?
Related
I have two classes:
One is User
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Subscription> Subscriptions { get; set; }
}
Other is Subscription:
public class Subscription
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
As you can see that User has a list of Subscriptions.
Now when using the entity framework code first approach I am getting a table for User which doesn't contain Subscriptions but a new column for User Id is being added to Subscription table. I was expecting to have a third table which contains two columns one with User ID and the other with subscription ID.
How can I achieve this?
From documentation:
Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.
So this answer is correct.
I just corrected code a little bit:
class MyContext : DbContext
{
public DbSet<Use> Users { get; set; }
public DbSet<Subscription> Subscriptions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserSubscription>()
.HasKey(t => new { t.UserId, t.SubscriptionId });
modelBuilder.Entity<UserSubscription>()
.HasOne(pt => pt.User)
.WithMany(p => p.UserSubscription)
.HasForeignKey(pt => pt.UserId);
modelBuilder.Entity<UserSubscription>()
.HasOne(pt => pt.Subscription)
.WithMany(t => t.UserSubscription)
.HasForeignKey(pt => pt.SubscriptionId);
}
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<UserSubscription> UserSubscriptions{ get; set; }
}
public class Subscription
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public List<UserSubscription> UserSubscriptions{ get; set; }
}
public class UserSubscription
{
public int UserId { get; set; }
public User User { get; set; }
public int SubscriptionId { get; set; }
public Subscription Subscription { get; set; }
}
PS. You don't need use virtual in navigation property, because lazy loading still not available in EF Core.
Create a third middle table named: UserSubscriptions for example.
public class User
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public virtual ICollection<UserSubscription> Subscriptions { get; set; }
}
public class Subscription
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class UserSubscription
{
public int ID { get; set; }
public int SubscriptionID { get; set; }
public decimal Price { get; set; }
public int UserID { get; set; }
public virtual User { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
}
Second Solution:
Add reference for Subscription to User and name it CurrentSubscription for example.
public class User
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int CurrentSubscriptionID { get; set; }
public virtual Subscription Subscription { get; set; }
}
public class Subscription
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
I have been reading about Entity Framework during the pass few weeks. I came across TPT subject. I am a little bit confused and have difficulty to differentiate between TPT and Navigation. When should we choose one over another. Please take a look at the code below.
A. Navication
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public List<ContractEmployee> ContractEmployees { get; set; }
public List<PermanentEmployee> PermanentEmployees { get; set; }
}
public class ContractEmployee
{
public int HourlyWorked { get; set; }
public int HourlyPay { get; set; }
public Employee Employee { get; set; }
}
public class PermanentEmployee
{
public int AnnualSalary { get; set; }
public Employee Employee { get; set; }
}
B. TPT
[Table("Employee")]
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
}
[Table("ContractEmployee")]
public class ContractEmployee : Employee
{
public int HourlyWorked { get; set; }
public int HourlyPay { get; set; }
}
[Table("ContractEmployee")]
public class PermanentEmployee : Employee
{
public int AnnualSalary { get; set; }
}
My question is about how can i select some one-two column from those tables are included and at the end when i am selecting as list it is returning list of parent object but child are contain those column i mention to select?
var testq = _db.Homes
.Include(x => x.Indexs.Cities.Proviences.Regions)
.Include(x => x.Images)
.Select(x => new Homes {
Images = x.Images,
Address = x.Address,
Indexs.Cities.Proviences.Regions =
x.Indexs.Cities.Proviences.Regions.Name });
At the end I need to have list of home model (List) and just images and Address and region name have value and important just those are selected from database not all infromation in the tables. I am trying to make a query with better performance
Edit Add Models
public partial class dbContext : DbContext
{
public virtual DbSet<City> Cities { get; set; }
public virtual DbSet<Province> Provinces { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Index> Indexs { get; set; }
public virtual DbSet<Home> Homes { get; set; }
public virtual DbSet<Images> Imageses { get; set; }
}
public partial class Home
{
public Home()
{
Imageses = new HashSet<Images>();
}
[Key]
public int IDHome { get; set; }
[Required]
[StringLength(5)]
public string Cap { get; set; }
[Required]
[StringLength(10)]
public string Number { get; set; }
[Required]
[StringLength(50)]
public string Address { get; set; }
....
public virtual Index Indexs { get; set; }
public virtual ICollection<Images> Imageses { get; set; }
}
public class Index
{
public int ID { get; set; }
public int IDHome { get; set; }
....
public virtual City Cities { get; set; }
}
public partial class City
{
[Key]
public int ID { get; set; }
public int IDProvincia { get; set; }
public decimal Latitudine { get; set; }
public decimal Longitudine { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
....
public virtual Province Provinces { get; set; }
}
public partial class Province
{
[Key]
public int ID { get; set; }
public int IDRegione { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(3)]
public string Init { get; set; }
...
public virtual Region Regions { get; set; }
}
public partial class Region
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public DateTime DataInsert { get; set; }
...
}
public class Images
{
public int ID { get; set; }
public string Path { get; set; }
...
}
absolutely tables have more column just add here as example
you have to define a new type with the fields you need, or use an anonymous type.
.Select(x => new {
Images = x.Images,
Address = x.Address,
Indexs.Cities.Proviences.Regions =
x.Indexs.Cities.Proviences.Regions.Name });
I have an EF Code First test app. I want to make one-to-many associations between 3 tables. I want to make a schema which looks like this http://gyazo.com/7a1800230a3838adecaafc5cb6676b25.png. When i launch my app VS says me:
The ForeignKeyAttribute on property 'EducationLevels' on type 'ConsoleApplication2.Employee' is not valid. The foreign key name 'EducationLevelId' was not found on the dependent type 'ConsoleApplication2.EducationLevel'. The Name value should be a comma separated list of foreign key property names.
Here it is my code:
class Program
{
static void Main(string[] args)
{
using (EmployeesContext context = new EmployeesContext())
{
Profession p = new Profession { Id = 0, NameOfProfession = "myprof" };
context.Profession.Add(p);
context.SaveChanges();
}
}
}
public enum Sex { Man = 0, Woman = 1 }
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public byte Age { get; set; }
public Sex Sex { get; set; }
public int EducationLevelId { get; set; }
public int ProfessionId { get; set; }
[ForeignKey("EducationLevelId")]
public virtual ICollection<EducationLevel> EducationLevels { get; set; }
[ForeignKey("ProfessionId")]
public virtual ICollection<Profession> Professions { get; set; }
}
public class EducationLevel
{
[Key]
public int Id { get; set; }
public string Level { get; set; }
public virtual Employee Employees { get; set; }
}
public class Profession
{
[Key]
public int Id { get; set; }
public string NameOfProfession { get; set; }
public virtual Employee Employees { get; set; }
}
public class EmployeesContext : DbContext
{
public DbSet<Employee> Employee { get; set; }
public DbSet<EducationLevel> EducationLevel { get; set; }
public DbSet<Profession> Profession { get; set; }
}
You need to swap collection and reference navigation properties (an Employee has one EducationLevel and one Profession, not many, and an EducationLevel has many Employees and not one, and a Profession has many Employees and not one):
public class Employee
{
// ...
public int EducationLevelId { get; set; }
public int ProfessionId { get; set; }
[ForeignKey("EducationLevelId")]
public virtual EducationLevel EducationLevel { get; set; }
[ForeignKey("ProfessionId")]
public virtual Profession Profession { get; set; }
}
public class EducationLevel
{
// ...
public virtual ICollection<Employee> Employees { get; set; }
}
public class Profession
{
// ...
public virtual ICollection<Employee> Employees { get; set; }
}
I have few Domain Models - Address, Customer, Employee, StoreLocation. Address has many to one relationship with Customerand Employee and one to one relationship with StoreLocation.
public class Address
{
public int Id;
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Address> Addresses { get; set; }
}
public class StoreLocation
{
public int Id { get; set; }
public string ShortCode { get; set; }
public string Description { get; set; }
public Address Address { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Dob { get; set; }
public IList<Address> Addresses { get; set; }
}
How to Map this relationship?. I am using ASP.NET MVC 3.0 and Entity Framework 4.1.
If you are using code-first (I think you want this, else, you have to edit your Q), the first way is the way explained below:
Entities:
public class Address {
[Key]
public int Id { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public virtual Customer Customer { get; set; }
public virtual StoreLocation StoreLocation { get; set; }
public virtual Employee Employee { get; set; }
public int? CustomerId { get; set; }
public int? EmployeeId { get; set; }
}
public class Customer {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class StoreLocation {
[Key]
public int Id { get; set; }
public string ShortCode { get; set; }
public string Description { get; set; }
public virtual Address Address { get; set; }
}
public class Employee {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime Dob { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
DbContext inherited class:
public class ManyOneToManyContext : DbContext {
static ManyOneToManyContext() {
Database.SetInitializer<ManyOneToManyContext>(new ManyOneToManyInitializer());
}
public DbSet<Address> Addresses { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<StoreLocation> StoreLocations { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Entity<Customer>().HasMany(c => c.Addresses).WithOptional(a => a.Customer).HasForeignKey(a => a.CustomerId);
modelBuilder.Entity<StoreLocation>().HasRequired(s => s.Address).WithOptional(a => a.StoreLocation).Map(t => t.MapKey("AddressId"));
modelBuilder.Entity<Employee>().HasMany(e => e.Addresses).WithOptional(a => a.Employee).HasForeignKey(e => e.EmployeeId);
}
}
Context Initializer:
public class ManyOneToManyInitializer : DropCreateDatabaseAlways<ManyOneToManyContext> {
protected override void Seed(ManyOneToManyContext context) {
}
}
That will create the db-schema below:
Let me know if you have any questions or need clarifications on any part.