ASP MVC 4 Mapping one to one relationship code first - asp.net-mvc-4

I am new to ASP MVC and am working on a project with complex related data model. so while working on the relationships i looked online and got the following example on the Blog of asps.net :
namespace CodeFirst.Associations.OneToOneFK
{
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int BillingAddressId { get; set; }
public int DeliveryAddressId { get; set; }
public Address BillingAddress { get; set; }
public Address DeliveryAddress { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
}
So my doubt is do we really need both the int BillingAddressID as well as Address BillingAddress?
Also, how do we associate an address to a user if we don't use AddressID.
Thanks for the help. :)

int BillingAddressID is called a foreign key property.
BillingAddress is called a navigation property (in this case a reference navigation property).
Foreign key properties aren't required to define a relationship, but they do simplify certain coding patterns. The general recommendation is to use both navigation properties and foreign key properties.
See here for more information about why FK associations were introduced.

Related

Can I reference single foreign key on multiple columns in a table? If yes, how to configure it in Entity Framework core

How can I generate above table like structure using Entity Framework core?
I am using code first approach to generate my tables from domain models which are as follows
public class Contact
{
public int ContactId { get; set; }
public string Email { get; set; }
public string Name { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
[ForeignKey("Contact")]
public int FirstContact { get; set; }
[ForeignKey("Contact")]
public int SecondContact { get; set; }
[ForeignKey("Contact")]
public int ThirdContact { get; set; }
public virtual Contact Contact { get; set; }
}
In the company table, I want foreign key on columns 'FirstContact', 'SecondContact', 'ThirdContact' which can refer to Contacts table.
I have also tried Fluent API but no success in same also.
Whenever I am running the add-migration command, I am getting this error:
There are multiple properties with the [ForeignKey] attribute pointing to navigation 'Company.Contact'. To define a composite foreign key using data annotations, use the [ForeignKey] attribute on the navigation.
I would appreciate any help regarding the same.
Thanks.
For multiple Navigation Properties, you need multiple Foreign Keys. EG
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public virtual Contact FirstContact { get; set; }
public virtual Contact SecondContact { get; set; }
public virtual Contact ThirdContact { get; set; }
}
And let EF Core create shadow properties for your FKs or with Foreign Key properties:
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int FirstCotactId {get; set;}
public virtual Contact FirstContact { get; set; }
public int SecondCotactId {get; set;}
public virtual Contact SecondContact { get; set; }
public int SecondCotactId {get; set;}
public virtual Contact ThirdContact { get; set; }
}

Doubts about EF Core 2.1 Relations

I am working on Entity Framework Core Code First approach and ASP.Net Core 2.1 making 3 tables:
Person class
public class Person
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public PeopleProfessions PeopleProfessions { get; set; }
}
Professions' class
public class Profession
{
public string Id { get; set; }
public string Name{ get; set; }
public PeopleProfessions PeopleProfessions { get; set; }
}
peopleprofessions' class
public class peopleprofessions
{
[ForeignKey("PersonId ")]
public string PersonId { get; set; }
public ICollection<Person> People { get; set; }
[ForeignKey("ProfessionId")]
public string ProfessionId{ get; set; }
public ICollection<Profession> Professions { get; set; }
}
On my Context:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<peopleprofessions>().HasKey(up => new { up.PersonId, up.ProfessionId });
}
Bearing this in mind:
People can have multiple professions.
The professions table is only for reading stored data like "Accountant".
I have doubts about how I can make table 3 only contain the foreigners and that it can meet the needs that I just mentioned.
I have tried to make the relationship appropriately but I also noticed that in tables 1 and 2 it requests both Id of the table people's professions.
I don't know if I am lost or if I am looking wrong or if there is an alternative to that situation. Thanks for any help you can give me.
You have the use of Collections on the navigation items a bit backwards. For your primary entities (Person and Profession), they should have collections, since it's one-to-many. But for the PeopleProfessions, each record is a single link to a specific entity, so no collection there just a direct object reference.
public class Person
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<PeopleProfessions> PeopleProfessions { get; set; }
}
public class Profession
{
public string Id { get; set; }
public string Name{ get; set; }
public ICollection<PeopleProfessions> PeopleProfessions { get; set; }
}
public class PeopleProfessions
{
public string PersonId { get; set; }
public Person Person { get; set; }
public string ProfessionId { get; set; }
public Profession Profession { get; set; }
}
You can, but don't need to specify a ForeignKey attribute because you are following EFs naming conventions(it will figure it out for you). Your OnModelCreating looks correct for the composite key.
You may want to consider removing the plural from PeopleProfessions (just call the class PeopleProfession) since one instance represents a single People-Profession relationship. I typically do this and but the navigation name in the entities remains plural, since it can represent more than one, i.e.
public ICollection<PeopleProfession> PeopleProfessions { get; set; }

EntityFrameworkCore - Classes and Entity distinction

Just been writing up my models and dbcontext using a code first approach for EFCore and i've hit a small problem... specifically with classes and generating migrations.
It seems with entityframework any class is seen as an entity/table (my assumptions so far) but what if I want a class to be a list of fields extended onto my entity?
For example:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public Address AddressDetails { get; set; }
}
public class Address {
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
}
How can I mark the address class as additional fields to the person entity as opposed to a separate entity?
Cheers,
Mark

'FK_Ratings_Users_UserId' on table 'Ratings' may cause cycles or multiple cascade paths

I am trying in .NET EFCore the following Code-First migrations through the entities below
User
[Table("Users")]
public class User
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string FirstName { get; set; }
[Required]
[MaxLength(100)]
public string LastName { get; set; }
[Required]
[MaxLength(250)]
public string Email { get; set; }
[Required]
[MinLength(8), MaxLength(16)]
public string Password { get; set; }
[Required]
[MinLength(6), MaxLength(15)]
public string Phone { get; set; }
public ICollection<Apartment> Apartments { get; set; }
public ICollection<Rating> Ratings { get; set; }
}
Apartment
[Table("Apartments")]
public class Apartment
{
[Key]
public int Id { get; set; }
[Required]
[MinLength(24), MaxLength(100)]
public string Title { get; set; }
[Required]
[MinLength(24), MaxLength(250)]
public string Address { get; set; }
[Required]
public int Price { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
public User User {get; set;}
public ICollection<Rating> Ratings { get; set; }
public ICollection<AptCateg> AptsCategs { get; set; }
}
Ratings
[Table("Ratings")]
public class Rating
{
[Key]
public int Id { get; set; }
public int Value { get; set; }
[ForeignKey("Apartment")]
public int ApartmentId { get; set; }
public Apartment Apartment { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
public User User { get; set; }
}
I use the commands dotnet ef migrations add InitialDatabase but when I try to use dotnet ef database update it throws the following error in cmd, as in the title
'FK_Ratings_Users_UserId' on table 'Ratings' may cause cycles or
multiple cascade paths
I tried adding as in the EFCore tutorial from here the modelBuilder's Cascade behavior but it doesn't work because I am getting the same error. I have also tried doing the answer from here but the implementation for HasRequired isn't working even if try to install EntityFrameworkCore.Tools.
I understand that there is an issue with a circular thingy going on. From my intuition the program doesn't know what to do in the case of deleting a user, if to drop or not its ratings and apartments or some of that sort, and this is why its acting this way but I can't fix the problem.
My question is, how can I solve this issue as I cannot create my database, and thus I cannot continue working on the project.
Thanks!
You'll have to make the user relationship optional on one of the tables like:
public int? UserId { get; set; }
Making the property type nullable tells EF that a cascade delete is not required here.
You are causing a cyclic reference by adding the User and Apartment to the Ratings entity. User and Apartment entities already have a one-to-many relationship to the Ratings collection.
'FK_Ratings_Users_UserId' on table 'Ratings' may cause cycles or
multiple cascade paths
This is how the Ratings entity should look like:
[Table("Ratings")]
public class Rating
{
[Key]
public int Id { get; set; }
public int Value { get; set; }
}

MVC4 how to load related data without Navigation Properties

I an fairly new to MVC, and have created an MVC4 application using EF-database-first. The database does not contain foreign key definitions and I can't add them (I don't own the database). Here are two example classes from the database:
public partial class Allocation
{
public int AllocID { get; set; }
public int DeptID { get; set; }
public decimal AllocationPercent { get; set; }
}
public partial class Department
{
public int DeptID { get; set; }
public string DeptName { get; set; }
public string Account { get; set; }
}
The default Allocation Index page shows the department ID. I want to show the department name instead. How can I do this without navigation properties?
I tried
public class AllocationController : Controller
{
private Entities db = new Entities();
//
// GET: /Allocation/
public ActionResult Index()
{
return View(db.Allocation.Include(d => d.DeptID).ToList());
}
...
but this gives an error ("A specified Include path is not valid. The EntityType 'TESTModel.Allocation' does not declare a navigation property with the name 'DeptID'.")...
I'm not sure how to code eager-loading or explicit-loading without navigation properties either, which prompted this question. Efficiency-wise, I don't believe it matters which way I load the related information, so any help in any direction would be appreciated.
The database does not have to have definitions, as long as the fields are there and the entities have been placed in the database with referential integrity in mind. All you need to do is let entity framework know about the relationship. This is done with the virtual keyword to create "Navigational Properties".
public partial class Allocation
{
public int AllocID { get; set; }
public int DeptID { get; set; }
public decimal AllocationPercent { get; set; }
public virtual Department Department { get; set; } /* this is your nav property */
}
public partial class Department
{
public int DeptID { get; set; }
public string DeptName { get; set; }
public string Account { get; set; }
}
Now you can do:
db.Allocation.Include(a => a.Department).ToList()
There may be an error which requires you to use a foreign key definition (although I do not think so). If this is the case, you will need to decorate your navigation property like this
[ForeignKey("DeptID")]
public virtual Department Department { get; set; }
You may also try it this way:
public int AllocID { get; set; }
[ForeignKey("Department")]
public int DeptID { get; set; }
public decimal AllocationPercent { get; set; }
public virtual Department Department { get; set; }
With navigation properties, Travis J's answer is what you need.
If you don't want to use navigation properties, assuming your DB context has a set called Departments, you could do smth like this:
var deptId = db.Allocation.DeptID;
var departments = db.Departments.Where(p => p.DeptID == deptId);
return View(departments.ToList());