Retrieving data from a different connection after logging in? - c#

I am building a holiday tracking website.
I have two data connections in my mvc application.
DeafultConnection which contains aspnetusers which I am using for user logins and Registrations.
Then LotusWorksEntities which I am using to track Employee details such as holiday requests, hours taking etc.
In DefaultConnections under aspnetusers, there's a column for email.
In LotusWorksEntitles under Employee Table, there's also a column for email.
On my Admin view page, I have a list of all Employees which has a column for Site.
I want Admins who have been assigned certain sites to only see employees from those assigned sites.
I have done this manually by
public ActionResult Index()
{
var employees = db.Employees.Include(e => e.Area).Include(e => e.Discipline).Include(e => e.Shift).Include(e => e.Site).Where(e => e.SiteID == 2);
return View(employees.ToList());
}
Is there a way that I could connect these two connections, so that when an admin logs in, it knows what site they've been assigned to and displays those employees under that site.
Here are my models:
public partial class Employee
{
public int EmployeeID { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public System.DateTime StartDate { get; set; }
public int RoleID { get; set; }
public int ShiftID { get; set; }
public int AreaID { get; set; }
public int DisciplineID { get; set; }
public int SiteID { get; set; }
public int ALCategory { get; set; }
public int HoursTaken { get; set; }
public Nullable<int> AwardedLeave { get; set; }
public Nullable<int> TotalHoursThisYear { get; set; }
public int HoursCarriedForward { get; set; }
public Nullable<int> EntitlementRemainingThisYear { get; set; }
public string Comments { get; set; }
public int SickLeaveTaken { get; set; }
public Nullable<int> SickLeaveEntitlement { get; set; }
public Nullable<int> SickLeaveEntitlementRemaining { get; set; }
public int StudyLeaveEntitlement { get; set; }
public int StudyLeaveTaken { get; set; }
public Nullable<int> StudyLeaveRemaining { get; set; }
public int ExamLeaveTaken { get; set; }
public int ForceMajeure { get; set; }
public int BereavementLeaveTaken { get; set; }
public int MaternityLeaveTaken { get; set; }
public int ParentalLeaveTaken { get; set; }
public int AdoptionLeaveTaken { get; set; }
public string ManagerEmail { get; set; }
public string AreaManagerEmail { get; set; }
public virtual Area Area { get; set; }
public virtual Discipline Discipline { get; set; }
public virtual Shift Shift { get; set; }
public virtual Site Site { get; set; }
}
Then my Site Model is:
public partial class Site
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Site()
{
this.Employees = new HashSet<Employee>();
}
public int SiteID { get; set; }
public string SiteName { get; set; }
public string SiteManager { get; set; }
public string SiteDelegate { get; set; }
public string SiteAdmin { get; set; }
public string SiteLocation { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employee> Employees { get; set; }
}
Employee Table and Site Table are connected through a foreign key.

Not completely understood which two connections you have is it database connection you are talking about?
But anyways you can use Linq joins to connect two separate list of objects in C#. filter data. Basically your two list should have some relation for join to work.
Here it is explained how to join two list in memory.

Related

Query with four tables in ASP.net using lambda expression

I have a web page that allows user to sign petitions, in the user detail page I want to display the petitions the user has signed, including the petition image. The image is specific to the category of the petition.
I have a category model that holds the image
public class Category
{
public int CategoryID { get; set; }
public string Name { get; set;}
public string catImage { get; set; }
public ICollection<Cause> Causes { get; set; }
}
Then I have a cause model that links to the Category through CategoryID
public class Cause
{
public int CauseID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public string createdBy { get; set; }
public DateTime createdOn { get; set; }
public int Target { get; set; }
public int CategoryID { get; set; }
public virtual ICollection<Signature> Signatures { get; set; }
public Category Category { get; set; }
}
Then a signature model that links the Cause to the User
public class Signature
{
public int SignatureID { get; set; }
public int CauseID { get; set; }
public int UserID { get; set; }
public DateTime signedOn { get; set; }
public virtual Cause Cause { get; set; }
public virtual User User { get; set; }
}
And finally a user model
public class User
{
public int ID { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string UserImage { get; set; }
public Role Role { get; set; }
public virtual ICollection<Signature> Signatures { get; set; }
}
On the user details page I am trying to display a table with a list of all the petitions the user has signed. I have been able to show the name and the date shown, but not the images.
I would really appreciated any help.
Thanks

SQL Exception trying to add an existing user when context.SaveChanges() on a different table

I am trying to add an entry to a table that holds a users browsing history information. However, when trying to save the addition an SqlException is thrown:
Cannot insert duplicate key row in object 'dbo.AspNetUsers' with
unique index 'UserNameIndex'. The duplicate key value is
(exampleUserName). The statement has been terminated.
A user is has many browsing histories but a browsing history can only be attached to one user so there is a user as part of the BrowsingHistory DataModel:
namespace DataModels
{
[Table("BrowsingHistory")]
public class BrowsingHistory
{
[Key]
public int BrowsingHistoryId { get; set; }
public int ProductId { get; set; }
public System.DateTime DateTime { get; set; }
public int DeviceId { get; set; }
public int UserId { get; set; }
public virtual AspNetUsers User { get; set; }
public virtual Device Device { get; set; }
public virtual Product Product { get; set; }
}
}
It is to note that I am using the Microsoft Identity classes for my authentication. The user class looks as follows:
namespace DataModels
{
using System;
using System.Collections.Generic;
[Table("AspNetUsers")]
public class AspNetUsers
{
public AspNetUsers()
{
BrowsingHistories = new HashSet<BrowsingHistory>();
Orders = new HashSet<Order>();
AspNetUserClaims = new HashSet<AspNetUserClaims>();
AspNetRoles = new HashSet<AspNetRoles>();
}
[Key]
public int Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string HouseName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string ContactNumber { get; set; }
public virtual ICollection<BrowsingHistory> BrowsingHistories { get; set; }
public virtual ICollection<Order> Orders { get; set; }
public virtual ShoppingCart ShoppingCart { get; set; }
public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetRoles> AspNetRoles { get; set; }
}
}
The error occurs when trying to save the addition in the repository. On the _context.SaveChanges() line the method below.
public void CreateBrowsingHistoryEntry(BrowsingHistory bhe)
{
_context.BrowsingHistory.Add(bhe);
_context.SaveChanges();
}
Any help with this issue would be greatly appreciated.

How to setup a relational data model?

I am completely new to ASP.NET and was trying to cross-reference two different models with each other. I have 'Customer':
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Zipcode { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
and 'Reservation':
public class Reservation
{
public int ReservationID { get; set; }
public string PetName { get; set; }
public DateTime Birthdate { get; set; }
public string Specie { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Customer Customer { get; set; }
}
Now, each Reservation should belong to a Customer (as you can see in the bottom line of the Reservation model) and should therefore contain the CustomerID. On the other hand should each Customer contain references to each Reservation that was made by him.
How can I setup this relation?
Use an ICollection for a one to many relationship.
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Zipcode { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
Note I originally suggested a generic list, but there's a few subtle differences.

How can I connect the fields of two tables in MVC 5?

I have two models and for which I will create tables through migration and database update. My first model is named Service, and it consists of these fields:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public int Count { get; set; }
}
My second model is called Business, and it has the following fields:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}
The point is that I want to add Category and Subcategory fields into my Business model, but the values of Category and Subcategory fields, should be one of the values inside the Service table's values for Category and Subcategory.
Simply, I want to connect those two fields. How can I achieve it? Should I just put a Service property inside the Business model?
Break out a separate entity for "Category" and then use foreign keys:
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Service
{
...
public virtual Category Category { get; set; }
public virtual Category Subcategory { get; set; }
}
// Do the same when adding category/subcategory fields to `Business`
If you want to ensure that these categories are only tied to Service (and you potentially have other types of categories or something) you can always just make the entity ServiceCategory or something and only create a relationship to it from Service.
You need to separate your break out your database to store lookup table for category and a lookup table for subcategory.
Then you can create:
public class Category {
public int CategoryId { get; set; }
public string Name { get; set; }
}
public class SubCategory {
public int SubCategoryId { get; set; }
public string Name { get; set; }
}
Then change your service class to:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public int CategoryId { get; set; }
public int SubcategoryId { get; set; }
public int Count { get; set; }
}
and change your Business class to:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}

Error with Entity Framework 4 and MVC 3

I have a database with 3 tables:
Subjects
Members
Topics
Then I added the connection string to web.config and created an EF with the following classes:
namespace MySite.Models
{
public class MySiteDBModel : DbContext
{
public DbSet<Topic> Topics { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Member> Members { get; set; }
public DbSet<TopicDataModel> TopicDataModel { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class Topic
{
[Key]
public int TopicID { get; set; }
public int SubID { get; set; }
public int MemberID { get; set; }
public string TDate { get; set; }
public string Title { get; set; }
public string FileName { get; set; }
public int Displays { get; set; }
public string Description { get; set; }
public virtual Subject Subject { get; set; }
public virtual Member Member { get; set; }
public virtual ICollection<TopicView> TopicView { get; set; }
}
public class Subject
{
[Key]
public int SubID { get; set; }
public string SubName { get; set; }
public virtual ICollection<Topic> Topic { get; set; }
}
public class Member
{
[Key]
public int MemberID { get; set; }
public string FLName { get; set; }
public string Email { get; set; }
public string Pwd { get; set; }
public string About { get; set; }
public string Photo { get; set; }
public virtual ICollection<Topic> Topic { get; set; }
}
public class TopicDataModel
{
[Key]
public int TopicID { get; set; }
public string SubName { get; set; }
public string FLName { get; set; }
public string TDate { get; set; }
public string Title { get; set; }
public int Displays { get; set; }
public string Description { get; set; }
}
}
Now when I am trying to query the database with the this code:
public ActionResult Index()
{
var topics = from t in db.Topics
join s in db.Subjects on t.SubID equals s.SubID
join m in db.Members on t.MemberID equals m.MemberID
select new TopicDataModel()
{
TopicID = t.TopicID,
SubName = s.SubName,
FLName = m.FLName,
TDate = t.TDate,
Title = t.Title,
Displays = t.Displays,
Description = t.Description
};
return View(topics.ToList());
}
I got this Error:
The model backing the 'MySiteDBModel' context has changed since the
database was created. Either manually delete/update the database, or
call Database.SetInitializer with an IDatabaseInitializer instance.
For example, the DropCreateDatabaseIfModelChanges strategy will
automatically delete and recreate the database, and optionally seed it
with new data.
Please help me!!!!!!
You need to set some controls on how EF is handling changes to your data model. Julie Lerman has a good blog post on Turning Off Code First Database Initialization Completely.
Also, here is a good overview - Inside Code First Database Initialization

Categories