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

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
}

Related

How to use 2 entity tables together?

I am working on school project which is about showing some database properties that I learned.I have 2 entity classes called Person and CarInformation.I want to show Name, Location,WhishedDays from Person and Brand, PlateNumber from CarInformation,together.
I tried generating new class called then I grouped Name, Location, WishedDays,Brand,PlateNumber.In the corresponding controller, I made a List with Select function but failed.
CarInformation Entity Class
public int Id { get; set; } //Primary key of carinfo table
public string Brand{ get; set; }
public string PlateNumber { get; set; }
public int Milage { get; set; }
public string InsuranceCompany{ get; set; }
public double ConsumptionPerMile { get; set; }
public int DailyPrice { get; set; }
public DateTime AvailableDates { get; set; }
[ForeignKey("Persons")]
public int OwnerId { get; set; } //foregein key (Person table to carinfo table)
public virtual Person Persons { get; set; } //Navigation property
public List<Sales> Sales { get; set; }
Person Entity Class
public int Id { get; set; } //primary key of person table
public string Name { get; set; }
public string Location { get; set; }
public int WishedDays { get; set; }
public virtual CarInformation Cars { get; set; } //Navigation property
public List<CarInformation> cars { get; set; } //bir insana ait birden fazla araba olabilir
public List<Sales> sales { get; set; }
Person-CarInformation Class
public string Name { get; set; }
public string Location { get; set; }
public int WishedDays { get; set; }
public string Brand { get; set; }
public string PlateNumber { get; set; }
Corresponding controller`s Index Method
public ActionResult Index()
{
var isimler = db.People.
Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});
return View(isimler.ToList());
}
When I execute in this circumstances I get this result
Brand and PlateNumber is empty.
Any advises?
Thank You.
https://imgur.com/D9a8whD
You haven't included dependent entity while fetching data. You can get it by changing your code like shown below.
var isimler = db.People.Include("Cars").
Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});

Retrieve multiple list from grandchild entity using lambda

I've three entities, say Parent, Child & GrandChild. This GrandChild has got three lists(a,b & c).
How to retrive all these lists using "Include" in Entity Framework?
I can retrive one list like this: Include("Parent.Child.GrandChild.a"),
but when I add another Include like : Include("Parent.Child.GrandChild.b"), it throws an error.
How will i retrive all these lists in a single query?
My code is as follows:
objUserNew = objContaxt.ContextRegistration
.Include("listing.postlist.commentslist")
.Include(‌​"listing.postlist.taglist")
.Include("listing.postlist.knocklist")
.FirstOrDefault(‌​x => x.id == objUser.id);
public class registration
{
public int id { get; set; }
public string firstname { get; set; }
public forgtPass forgtPass { get; set; }
public List<listing> listing { get; set; }
}
public class listing
{
public int id { get; set; }
public string address { get; set; }
public List<post> postlist { get; set; }
}
public class post
{
public int id { get; set; }
public string imgUrl { get; set; }
public List<tag> taglist { get; set; }
public List<comments> commentslist { get; set; }
public List<knoqs> knoqs { get; set; }
}
public class tag
{
public string name { get; set; }
}
public class comments
{
public int id { get; set; }
public string comment { get; set; }
public status status { get; set; }
}
public class knoqs
{
public int id { get; set; }
public virtual int registration_id { get; set; }
[ForeignKey("registration_id")] public registration registration { get; set; }
public status status { get; set; }
}

Code-First SQL Server ASP.NET MVC6

I am a VB.NET programmer, but I am trying to learn C# and MVC in my spare time. I am using ASP.NET MVC 5.1.0.0 and I am trying to do code-First database creation in a local instance of SQL Server.
I was able to get the first database table to update in the database when I ran Update-Database from within the IDE, but when I added a second table that has a PK/FK relationship with the first, I am getting a red line under [ForeignKey] which reads
Does not contain a constructor that takes 1 arguments
I have been searching all over and not getting anywhere. Any suggestions or help would be appreciated. By the way, the first table is a PK/FK relationship to the AspNetUsers table.
public class BuildDatabase : IdentityUser
{
public virtual Companies Companies { get; set; }
public virtual NotaryProfile NotaryProfile { get; set; }
}
public class Companies
{
[Key]
[Column("CompanyID")] // Did this as the database will reflect TableName_ColumnName instead.
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public bool IsActive { get; set; }
public bool IsNotary { get; set; }
public virtual ICollection<NotaryProfile> NotaryProfile { get; set; }
}
public class NotaryProfile
{
[Key]
public int NotaryID { get; set; }
public string NamePrefix { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public string NameSuffix { get; set; }
public bool IsActive { get; set; }
public int DefaultState { get; set; }
public int DefaultCounty { get; set; }
public bool IsSigningAgent { get; set; }
public bool HasABond { get; set; }
public decimal BondAmount { get; set; }
public bool HasEandO { get; set; }
public decimal EandOAmount { get; set; }
public bool ElectronicNotarizationsAllowed { get; set; }
public string ElectronicTechnologyUsed { get; set; }
public string ComissionNumber { get; set; }
public DateTime CommissionIssued { get; set; }
public DateTime CommssionOriginal { get; set; }
public DateTime CommissionExpires { get; set; }
public DateTime CommissionFiledOn { get; set; }
public string SOSAuditNumber { get; set; }
public string CommissionDesc { get; set; }
[Foreignkey("CompanyID")] // Companies.CompanyID = PK
public int CompanyID { get; set; } // PK/FK relationship.
public Companies Companies { get; set; } // Reference to Companies table above.
}
public class SchemaDBContext : IdentityDbContext<BuildDatabase>
{
public SchemaDBContext()
: base("DefaultConnection"){}
public DbSet<Companies> Companies { get; set; }
public DbSet<NotaryProfile> NotaryProfile { get; set; }
}
One of your classes (probably NotaryProfile) needs to reference another object (the foreign key relationship) but there is no constructor in that class that accepts an argument to establish that relationship, e.g.:
public NotaryProfile(int companyId) {
this.companyId = companyId;
}
BTW, a better way to establish that relationship is to use the actual class type rather than the ID, as in:
public class NotaryProfile {
...
public Company Company { get; set; }
// Instead of this:
// public int CompanyID { get; set; } // PK/FK relationship.
...
}
See also:
C# “does not contain a constructor that takes '1' arguments”
Does not contain a constructor that takes 2 arguments

Creating a Key Table and Domain Models

All,
I need to add a domain class for a new key table that relates a table of club members ([dbo].NewClubProspect) to emails ([dbo].NewClubEmail) sent to them.
I am not sure how to set this up in the domain classes.
Question
Need to annotate the key table (NewClubProspectNewClubEmail) Since both properties are foreign keys, not sure if I need an actual primary key, too? How do I annotate this?
Here is a diagram of how the tables relate. The table on the bottom of the diagram (NewClubProspectNewClubEmail) is the new table that I need to create in the database and in code, in a domain class.
Here are my domain classes (chopped down for brevity)
public class NewClub
{
public NewClub()
{
NewClubProspects = new List<NewClubProspect>();
NewClubEmails = new List<NewClubEmail>();
}
public int Id { get; set; }
public string NewClubName { get; set; }
public string NewClubLocation { get; set; }
public string NewClubType { get; set; }
public string NewClubCity { get; set; }
public string NewClubState { get; set; }
public string NewClubCountry { get; set; }
public virtual List<NewClubProspect> NewClubProspects { get; set; }
public virtual List<NewClubEmail> NewClubEmails { get; set; }
}
public class NewClubProspect
{
[Key]
public int Id { get; set; }
//Foreign Key
public int NewClubId { get; set; }
public bool IsConverted { get; set; }
public string ProspectFirstName { get; set; }
public string ProspectLastName { get; set; }
public string ProspectEmail { get; set; }
public virtual NewClub NewClub { get; set; }
public virtual List<NewClubEmail> NewClubEmails { get; set; }
}
public class NewClubEmail
{
//Primary key
[Key]
public int Id { get; set; }
//Foreign Key
public int NewClubId { get; set; }
public string Subject { get; set; }
public virtual List<NewClubProspect> Recipients { get; set; }
public string Body { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
public DateTime? SentDate { get; set; }
public NewClub NewClub { get; set; }
public NewClubEmail()
{
Recipients = new Collection<NewClubProspect>();
}
}
//---------------------------------------------------------
// Not sure what to do here. They are both foreign keys
//---------------------------------------------------------
public class NewClubProspectNewClubEmail
{
public int NewClubEmail_Id {get; set;}
public int NewClubProspect_Id {get; set;
}
Just mark both as Key:
[Key]
public int NewClubEmail_Id {get; set;}
[Key]
public int NewClubProspect_Id {get; set;}

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