EF Core only creates one self-referencing foreign key instead of 2 - asp.net-core

I am trying to create a model to represent missions in a game. When a mission is completed, another mission is played depending on which team won the mission. For example Mission1, if TeamA wins then you play Mission2, if TeamB wins then you play Mission3.
For each mission I want two self-referencing columns, TeamAWinMission and TeamBWinMission, which hold the foreign key to another mission.
The migrations only seem to recognise a single self-reference in the model.
This will create a column for TeamAWinMission:
public class Mission
{
public int Id { get; set; }
public string Name { get; set; }
public Mission TeamAWinMission{ get; set; }
}
This will only create a column for TeamBWinMission:
public class Mission
{
public int Id { get; set; }
public string Name { get; set; }
public Mission TeamAWinMission{ get; set; }
public Mission TeamBWinMission{ get; set; }
}
How can I make the migration generate columns/foreign keys for both of these?
Edit: Was able to resolve this with InverseProperty from https://stackoverflow.com/a/46832490/11575271

It seems that there is one-to-one self-reference relationship in Mission model , you could try to define the [ForeignKey]in your model like below :
public class Mission
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("TeamAWinMission")]
public int? TeamAWinMissionId { get; set; }
public Mission TeamAWinMission { get; set; }
[ForeignKey("TeamBWinMission")]
public int? TeamBWinMissionId { get; set; }
public Mission TeamBWinMission { get; set; }
}
Then use Include attribute to load related data in the controller :
public IActionResult Mission()
{
var result = _context.Missions
.Include(m => m.TeamAWinMission)
.Include(m => m.TeamBWinMission)
.ToList();
return View(result);
}
Reference : https://learn.microsoft.com/en-us/ef/core/querying/related-data

Related

How to establish one-to-many relationship for a code-first approach?

I'm trying to build a recipe app for my spouse. I'm trying to set it up so she can add new recipes to the database as the app grows.
When adding new recipe, she will have three drop-down to pick from to construct her new recipe ingredients. First one will contain a list of ingredients that she can choose from, the second one a list of measuring units and the third one a list of quantities.
Here is what I got so far. Am I heading in the right direction or am I off? I'm using Entity Framework with a code-first approach:
public class Recipes
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
}
public class Units model
{
[Key]
public int Id { get; set; }
public string UnitName { get; set; }
}
public class UnitQty
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class IngredientsModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class RecipeIngredients
{
public int Id { get; set; }
public int RecipesId { get; set; }
[ForeignKey("RecipesId")]
public Recipes Recipes { get; set; }
public int IngredientsModelId { get; set; }
[ForeignKey("IngredientsModelId")]
public IngredientsModel IngredientsModel { get; set; }
public int UnitQtyId { get; set; }
[ForeignKey("UnitQtyId")]
public UnitQty UnitQty { get; set; }
public int UnitsModelId { get; set; }
[ForeignKey("UnitsModelId")]
public UnitsModel UnitsModel { get; set; }
}
After creating the table, controller and the views, this is what I get in the recipe ingredients index view.
Any suggestion will be more than welcome please and thank you
RecipeIngredient class's view
First of all. You are over engineering your domain model. On relational databases Join is bottleneck you should prevent from joins if it doesn't helps you.
public class Recipt
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public ICollection<RecipeIngredient> Ingredients { get; set; }
}
public class IngredientModel
{
public int Id { get; set; }
public string Name { get; set; }
public IngredientUnit UnitType { get; set; } // Unit model is best to be added here. if it doesn't change in a single IngredientModel.
}
public class RecipeIngredient
{
public int Id { get; set; }
public int UnitQuantiy { get; set; } // No need to more classes.
public IngredientModel Model { get; set; }
public Recipt Recipt { get; set; }
}
public Enum IngredientUnitType // Same Unit Model but less database relation as its small finite collection.
{
Killogram,
Count,
....
}
and according to the Microsoft documents its best to use fluentApi configuration for the relations.
Override this method in your Context:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Recipt>.HasMany(P => P.Ingredients).WithOne(P => P.Recipt);
builder.Entity<RecipeIngredient>.HasOne(P => P.Model);
// There is no need to explicit foreign key definition. but you can explicitly define your foreign keys.
}
And for the last part. in Views you can use extra models called ViewModels.
As above domain turned to a minimal domain you just need to pass a list of IngredientModels to your view to complete your View.

How to set up relationship using entity framework core

I have Two Model
public class User: Entity
{
public string Gender { get; set; }
public string Name { get; set; }
}
And
public class CognitoUser : Entity
{
public string UserId { get; set; }
public User User{ get; set; }
public string CognitoName { get; set; }
}
I want to set Cognito.UserId as User.Id . I have written the following which is not working can you please correct me as i dont want to create a model CognitoUser into user model.
modelBuilder.Entity<CognitoUser>(e =>
{
e.ToTable("CognitoUser");
e.HasKey(p => p.UserId);
e.HasOne(x => x.User)
.HasForeignKey<User>(c => c.Id);
});
Primary keys are required in each Entity which is missing in your User Entity.
Using Fluent API is optional. If you set your classes right, Entity Framework will understand what you want to achieve.
Hints:
Use [Key] attribute to specify a property as primary key
Prefered primary key format would be {ClassName}{Id}
Use [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to force database
to automatically generate primary key for you.
You can use Guid as primary key type, it is always unique and hassle-free
Additionally, check out the code below to see how to create a relation.
public class User: Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public string Gender { get; set; }
public string Name { get; set; }
}
public class CognitoUser: Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CognitoUserId { get; set; }
public string CognitoName { get; set; }
// relation
public Guid UserId { get; set; }
public User User { get; set; }
}
Visualization:

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; }

'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; }
}

Automapper and EF Navigation Properties

With ASP.NET MVC Core and Entity Framework Core I'm trying to create a simple website.
I've defined my Model:
public class Club
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Team> Teams { get; set; }
}
public class Team
{
[Key]
public int Id { get; set; }
public int ClubId { get; set; }
[MaxLength(32)]
public string Name { get; set; }
public virtual Club Club { get; set; }
}
As well as the corresponding View Models:
public class ClubViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IEnumerable<TeamViewModel> Teams { get; set; }
}
public class TeamViewModel
{
public int Id { get; set; }
public int ClubId { get; set; }
public string Name { get; set; }
public virtual ClubViewModel Club { get; set; }
}
I've defined an Automapper Profile with the corresponding mappers:
CreateMap<Club, ClubViewModel>();
CreateMap<ClubViewModel, Club>();
CreateMap<Team, TeamViewModel>();
CreateMap<TeamViewModel, Team>();
I try to load a Club entity, with the navigation property Teams included (_context.Club.Include(c => c.Teams).ToList()). This works as expected, it returns a Club with a list of Teams. But when I try to map this instance to a ClubViewModel, I get an 502.3 error and my debug session is ended immediately.
It seems like I am missing something trivial, but I simply do not see it. There's no information in the Windows Event Log and I can't find any usefull information in the IIS Express logging (%userprofile%\documents\IISExpress)
What is causing the crash?
You can't perform this mapping because it is circular. You'll have to remove this line
public virtual ClubViewModel Club { get; set; }
from your TeamViewModel and the mapping should work as expected.