How to get data from 3 related entities using LINQ? - c#

I have a student class, program class and session class. I want to select a student on the basis of his rollno, sessionName, programName and password.
program and session classes have one to many relationship with student class.
This is Session Class.
public class Session
{
[Key]
public int SessionID { get; set; }
[Required]
[MaxLength(30)]
public string SessionName { get; set; }
//Relationship ------- Navigational Properties -------------------------------
public virtual List<Student> Students { get; set; }
public virtual List<Teacher> Teachers { get; set; }
public virtual List<Subject> Subjects { get; set; }
public virtual List<Program> Programs { get; set; }
}
This is program class.
public class Program
{
[Key]
public int ProgramID { get; set; }
[Required]
[MaxLength(30)]
public string ProgramName { get; set; }
//Relationship ------- Navigational Properties -------------------------------
public virtual List<Student> Students { get; set; }
public virtual List<Teacher> Teachers { get; set; }
public virtual List<Subject> Subjects { get; set; }
}
And this is Student Class.
public class Student
{
[Key]
[Column(Order = 0)]
public int StudentID { get; set; }
[Required]
[MaxLength(30)]
public string FirstName { get; set; }
[Required]
[MaxLength(30)]
public string LastName { get; set; }
[Required]
[MaxLength(30)]
public string UserName { get; set; }
[Required]
[MaxLength(35)]
public string Email { get; set; }
[Required]
[MaxLength(30)]
public string Password { get; set; }
[Required]
[MaxLength(30)]
public string FatherName { get; set; }
[Required]
public DateTime DOB { get; set; }
[Required]
[MaxLength(15)]
public string CNIC { get; set; }
[Required]
public int RollNo { get; set; }
public bool Active { get; set; }
public bool Graduated { get; set; }
public bool Expelled { get; set; }
//Relationship ------- Navigational Properties -------------------------------
public virtual List<Teacher> Teachers { get; set; }
public virtual List<Subject> Subjects { get; set; }
public virtual List<StudentMessage> Messages { get; set; }
public Session Session { get; set; }
public Program Program { get; set; }
public Grade Grade { get; set; }
public Attendance Attendance { get; set; }
public StudentContact StudentContact { get; set; }
public StudentMessage StudentMessage { get; set; }
}
Now how do I select student's username who has given specific rollno, sessionName, programName, password using LINQ Query Syntax and using LINQ Method syntax?
In database, Student Table contains SessionID and ProgramID.
I know "Join" is used to extract data from multiple tables but i don't know how to use it in LINQ Syntax.

You can use following code:
var list = dbContext.Students
.Where(e=>e.RollNo == 10)
.Where(e=>e.Password == "password")
.Where(e=>e.Session.SessionName == "SessionName")
.Where(e=>e.Session.ProgramName == "ProgramName")
.Select(e=> e.UserName)
.ToList();

Related

Entity Framework accessing data within include and .thenInclude

I am new to Entity Framework.
I understand the basics but am a little confused here.
await Context.PremiseContacts
.Include(c => c.Contact)
.ThenInclude(c => c.ContactEmails)
So imagine I have this code.
Contact is within premise contacts and then contact emails is within contact.
How would I access the contact emails data ?
I have tried this
Email = c.Contact.ContactEmails.,
when passing on the model but that is much options as I get and there should be more properties within contact email.
Essentially how do you access the data defined by .include and then how would you access the data defined by multiple includes/ then includes.
EDIT
Premise Contact
namespace SolaceSecure.DAL.Models
{
[Table("premiseContact")]
public partial class PremiseContact
{
[Key]
[Column("premiseId")]
public Guid PremiseId { get; set; }
[Key]
[Column("contactId")]
public Guid ContactId { get; set; }
[Column("isSolaceUser")]
public bool? IsSolaceUser { get; set; }
public virtual Contact Contact { get; set; }
public virtual Premise Premise { get; set; }
}
}
Contact
public Contact()
{
ContactEmails = new HashSet<ContactEmail>();
ContactPhoneNumbers = new HashSet<ContactPhoneNumber>();
PremiseComplianceContacts = new HashSet<PremiseComplianceContact>();
PremiseContacts = new HashSet<PremiseContact>();
}
[Key]
[Column("contactId")]
public Guid ContactId { get; set; }
[Required]
[Column("contactName")]
[StringLength(100)]
public string ContactName { get; set; }
[Column("contactDescription")]
[StringLength(250)]
public string ContactDescription { get; set; }
[Column("customerId")]
public Guid CustomerId { get; set; }
[Column("userId")]
public Guid? UserId { get; set; }
[Column("dateCreated", TypeName = "datetime")]
public DateTime DateCreated { get; set; }
[Column("dateModified", TypeName = "datetime")]
public DateTime? DateModified { get; set; }
[Column("modifiedBy")]
public Guid? ModifiedBy { get; set; }
[Column("isDeleted")]
public bool IsDeleted { get; set; }
[Column("createdBy")]
public Guid? CreatedBy { get; set; }
public virtual Person CreatedByNavigation { get; set; }
public virtual Customer Customer { get; set; }
public virtual Person ModifiedByNavigation { get; set; }
public virtual Person User { get; set; }
public virtual ICollection<ContactEmail> ContactEmails { get; set; }
public virtual ICollection<ContactPhoneNumber> ContactPhoneNumbers { get; set; }
public virtual ICollection<PremiseComplianceContact> PremiseComplianceContacts { get; set; }
public virtual ICollection<PremiseContact> PremiseContacts { get; set; }
Contact Email
{
[Table("contactEmail")]
public partial class ContactEmail
{
[Key]
[Column("contactEmailId")]
public Guid ContactEmailId { get; set; }
[Required]
[Column("email")]
[StringLength(100)]
public string Email { get; set; }
[Column("contactId")]
public Guid ContactId { get; set; }
[Column("emailTypeId")]
public Guid EmailTypeId { get; set; }
public virtual Contact Contact { get; set; }
}
}

How to effectively implement 1 to many relationship?

I have an EF model to is connected 1 to 1 for many tables but I am having trouble connecting a 1 to many table. Currently using EF6 on .Net 4.8. The error I am recieving is "Multiplicity is not valid in Role '' in relationship 'Login_Users'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'"
The main table is
Users
public partial class Users
{
public Users()
{
this.Login = new HashSet<Login>();
this.Phone = new HashSet<Phone>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public System.DateTime BirthDate { get; set; }
public int LastFourSSN { get; set; }
public Nullable<int> AddressId { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Login> Login { get; set; }
public virtual ICollection<Phone> Phone { get; set; }
}
One to one tables
public partial class Login
{
public Login()
{
this.Login_Track = new HashSet<Login_Track>();
this.Policy = new HashSet<Policy>();
}
public string Username { get; set; }
public string Password { get; set; }
[Key, ForeignKey("Users")]
public Nullable<int> UserId { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> LastLoginDate { get; set; }
public virtual Users Users { get; set; }
}
Address
public partial class Address
{
public Address()
{
this.Users = new HashSet<Users>();
}
[Key, ForeignKey("Users")]
public int Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public virtual ICollection<Users> Users { get; set; }
}
1 to many table
public partial class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Number { get; set; }
public string Type { get; set; }
[ForeignKey("Users")]
public Nullable<int> UserId { get; set; }
public virtual Users Users { get; set; }
}

Entity Framework 6 asp.net Code First Setup

Hi guys I am spinning wheels on this one. I am using EF6 and ASP.Net 4.6. I have a given table which has student information and parent information. A student can have many parents and a parent can have many students. Call this table 'Contact'. I am to create a table called 'Request' which will hold information for a parent submitting a request for his student. I will create a lookup table with two columns, one for student id and one for parent id called 'StudentParents'. I want to be able to have the parent log in, select his student from a drop down of all of his students and submit the request. The many to many relationship is throwing me off as far as my include statements. How can I get EF to set up this structure so that when I GetRequest(id) I can get the Student info and the Parent info to be included? Here is my code that wont Include anything other than the request.
public class Contact
{
[Key]
public int id { get; set; }
public string student_id { get; set; }//This is the Student ID
public string last_name { get; set; }
public string first_name { get; set; }
public string middle_initial { get; set; }
public string grade { get; set; }
public int current_school_id { get; set; }
public string current_school_name { get; set; }
[Display(Name = "Parent Last Name")]
public string contact_first_name { get; set; }
[Display(Name = "Parent Middle Name")]
public string contact_middle_name { get; set; }
[Display(Name = "Parent Last Name")]
public string contact_last_name { get; set; }
public string contact_relationship { get; set; }
[Display(Name = "Parent Email")]
public string contact_email { get; set; }
[Display(Name = "Parent Address")]
public string login { get; set; }//This is the Parent ID
public string Classif_description { get; set; }
}
public class Request
{
[Key]
public int id { get; set; }
public Student student_id { get; set; }
public Contact login { get; set; }
[Display(Name = "First School Choice")]
public string firstSchool { get; set; }
[Display(Name = "Second School Choice")]
public string secSchool { get; set; }
[Display(Name = "Rising Grade")]
public string rising_grade { get; set; }
public DateTime ReqSubmitted { get; set; }
public string ReqStatus { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public string ModifBy { get; set; }
}
public class Parent
{
public int id { get; set; }
public string contact_first_name { get; set; }
public string contact_middle_name { get; set; }
public string contact_last_name { get; set; }
public string contact_relationship { get; set; }
public string contact_email { get; set; }
public string contact_address { get; set; }
public string contact_city { get; set; }
public string contact_zip { get; set; }
[Key]
public string login { get; set; }
public string contact_pw { get; set; }
public string phone { get; set; }
public string phone_type { get; set; }
public Parent() { }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public int id { get; set; }
public int student_id { get; set; }
public string last_name { get; set; }
public string first_name { get; set; }
public string middle_initial { get; set; }
public DateTime birthdate { get; set; }
public string gender { get; set; }
public string grade { get; set; }
public string Fed_race_description { get; set; }
public string Classif_description { get; set; }
public int current_school_id { get; set; }
public string current_school_name { get; set; }
public int home_school_id { get; set; }
public string home_school_name { get; set; }
public Student()
{
this.Parents = new HashSet<Parent>();
}
public virtual ICollection<Parent> Parents { get; set; }
}
public class OEContext : DbContext
{
public OEContext() : base("name=OEContext")
{
}
public DbSet<Request> Requests { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.HasMany(s => s.Students)
.WithMany()
.Map(x =>
{
x.MapLeftKey("login");
x.MapRightKey("student_id");
x.ToTable("StudentParents");
}
);
base.OnModelCreating(modelBuilder);
}
}
Changed the strategy. Made Request have many Contacts. So I added a constructor to the request:
public Request()
{
Contacts = new List<Contact>();
}
public virtual ICollection<Contact> Contacts { get; set; }
Next I changed the contact class:
public int ContactId { get; set; }
public Contact() { }
public virtual Request Request { get; set; }
With this relationship I can pull both Parents and a student from the Contacts associated with the Request.

Entityframework navigation property insert

I have these models that ParentID foreign key for CustomerID
I want to insert an address for customer via navigation property
what should I do?
public partial class Customer
{
public long CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public partial class Address
{
public long AddressID { get; set; }
public long ParentID { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Address1 { get; set; }
public string PostalCode { get; set; }
public virtual Customer Customer { get; set; }
public virtual Supplier Supplier { get; set; }
}

Complex relationship mappings in entity framework

I am building a reservation system. I have users in roles('admin', 'client', 'employee', 'student').
Each reservation must be associated with a user of role client, it might be assigned to user of role employee and might also be assigned to user of role student.
So in my reservation class I have properties of type User and I have marked them with [ForeignKey("AnytypeId")] attribute to hint EF for relations.
I have seen code like this at http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public Service Service
{
get;
set;
}
public string EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public User Employee { get; set; }
public string ClientId { get; set; }
[ForeignKey("ClientId")]
public User Client { get; set; }
public string StudentId { get; set; }
[ForeignKey("StudentId")]
public User Student { get; set; }
}
public class User
{
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//public Guid UserId { get; set; }
[Key]
[Required(ErrorMessage = "User Name is required")]
[Display(Name = "User Name")]
[MaxLength(100)]
public string UserName { get; set; }
[Required]
[MaxLength(64)]
public byte[] PasswordHash { get; set; }
[Required]
[MaxLength(128)]
public byte[] PasswordSalt { get; set; }
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[MaxLength(200)]
public string Email { get; set; }
[MaxLength(200)]
public string Comment { get; set; }
[Display(Name = "Approved?")]
public bool IsApproved { get; set; }
[Display(Name = "Crate Date")]
public DateTime DateCreated { get; set; }
[Display(Name = "Last Login Date")]
public DateTime? DateLastLogin { get; set; }
[Display(Name = "Last Activity Date")]
public DateTime? DateLastActivity { get; set; }
[Display(Name = "Last Password Change Date")]
public DateTime DateLastPasswordChange { get; set; }
public string address { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Phone { get; set; }
public bool? IsActive { get; set; }
public int? ClientTypeID { get; set; }
public virtual ClientType ClientType { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public DateTime? PackageValidity { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
this.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(m =>
{
m.ToTable("RoleMemberships");
m.MapLeftKey("Username");
m.MapRightKey("RoleName");
});
}
}
Now as I run my mvc3 EF code first app database created for me on the fly with following ERD and edmx model.
Now few problems that I am having:
1. When I am listing all the users of role clients their reservation property is showing always 0 even if their are reservations available in database.
2. If I am trying to delete a user of role client who have reservation in database I get following error.
The DELETE statement conflicted with the REFERENCE constraint "Reservation_Client". The conflict occurred in database "CRSDB", table "dbo.Reservations", column 'ClientId'.
The statement has been terminated.
I checked the realtions in ERD and edmx model their is no cascade delete applied to them. How can I instruct EF to delete all the reservations when deleting user of role client but not for users of role employee or student.
This code does the trick
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public String PaymentMethod { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public virtual Service Service
{
get;
set;
}
public string EmployeeID { get; set; }
[ForeignKey("EmployeeID")]
public virtual User Employee { get; set; }
public string ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual User Client { get; set; }
public string StudentID { get; set; }
[ForeignKey("StudentID")]
public virtual User Student { get; set; }
}
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
this.HasOptional(r => r.Client).WithMany().WillCascadeOnDelete(true);
this.HasOptional(r => r.Employee).WithMany().WillCascadeOnDelete(false);
this.HasOptional(r=>r.Student).WithMany().WillCascadeOnDelete(false);
}
}

Categories

Resources