Extend Asp Net Core Identity Relation - asp.net-core

In Asp net core (3.1) Identity i want add a many to many relationship between user and TourOperators.
(The concept is that many user can follow many tour operators).
I have the tour operators class:
public class TourOperator
{
public int Id { get; set; }
public ICollection<Follow> Follows { get; set; }
}
I have extended the UserIdentity class:
public class ApplicationUser: IdentityUser
{
public ICollection<Follow> Follow { get; set; }
}
I have the Follow class:
public class Follow
{
public long Id { get; set; }
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int TourOperatorId { get; set; }
public TourOperator TourOperator{ get; set; }
}
After execute the migration, why in the Follow table i have 4 field instead of 3?
I have the following field:
I think that ApplicationUserId couldn't be present

Entity Framework has no way to link the UserId and ApplicationUser properties. So you either need to follow convention, whereby EF can make an educated guess. The simplest option is to rename your string property:
public string ApplicationUserId { get; set; }
Alternatively, you can configure it, for example using an attribute:
[ForeignKey("ApplicationUser"]
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
Or in the OnModelCreating method, for example:
modelBuilder.Entity<Follow>()
.WithOne(f => f.ApplicationUser)
.HasForeignKey("UserId");

Related

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:

How to retrieve the objects participating in a many-to-many relationship?

I have a many-to-many relationship between User(Contributor) and TaskType. I want to assign to a variable only TaskTypes that have the current user among their contributors. Obviously, I can somehow do this using the functionality of the Entity Framework. But how? I use asp.net core 3.
Below I try unsuccessfully to do it:
public IQueryable<TaskType> ContributedTaskTypes
{
get
{
// This code doesn't work!
return _dbContext.TaskTypes.Where(t => t.Contributors.Contains(c => c.UserId == CurrentUserId));
}
}
Below are definitions of all models involved in this relationship:
public class TaskType
{
public int Id { get; set; }
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public virtual List<Contribution> Contributors { get; set; }
}
public class Contribution
{
public int Id { get; set; }
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int TaskTypeId { get; set; }
public TaskType TaskType { get; set; }
}
public class ApplicationUser : IdentityUser
{
public virtual List<Contribution> ContributedToTaskTypes { get; set; }
}
For those queries it is always easiest to do queries where you can dot to the result.
Here is the query with sql-like syntax
from row in _dbContext.Contribution
where row.UserId == CurrentUserId
select row.TaskType
By selecting row.TaskType instead of just row you get it correct entity.
Is that Contributors property retrieved correctly from DB? if it is not you must call Include() method to load/refer relational referenced entities
_dbContext.TaskTypes.Include(p=>p.Contributors).Where(..
more: https://learn.microsoft.com/en-us/ef/core/querying/related-data
In Addition, if EF Core Table Relation is not correctly defined, you should follow
this instruction: https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx

Add custom fields for AspNetUser [duplicate]

This question already has answers here:
extend ASP.NET Core Identity user
(2 answers)
Closed 3 years ago.
I am a newbie in ASP.NET Core.
How can I add custom fields to my user model both in code and UI?
Current user management UI is something like this, but I want to add some extra fields, like credit or scores, in model, DB & UI:
And this is my AspNetUser model :
public partial class AspNetUsers
{
public AspNetUsers()
{
AspNetUserClaims = new HashSet<AspNetUserClaims>();
AspNetUserLogins = new HashSet<AspNetUserLogins>();
AspNetUserRoles = new HashSet<AspNetUserRoles>();
AspNetUserTokens = new HashSet<AspNetUserTokens>();
}
public string Id { get; set; }
public string UserName { get; set; }
public string NormalizedUserName { get; set; }
public string Email { get; set; }
public string NormalizedEmail { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string ConcurrencyStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public double Credit { get; set; }
public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogins> AspNetUserLogins { get; set; }
public virtual ICollection<AspNetUserRoles> AspNetUserRoles { get; set; }
public virtual ICollection<AspNetUserTokens> AspNetUserTokens { get; set; }
}
Custom user data is supported by inheriting from IdentityUser. It's customary to name this type ApplicationUser:
public class ApplicationUser : IdentityUser
{
public string CustomTag { get; set; }
}
The detail steps to customize could be found in Customize the model document .
In ASP.NET Core 2.1 or later, Identity is provided as a Razor Class Library. For more information, see Scaffold Identity in ASP.NET Core projects .
After scaffolding , you can find the profile page in Areas.Identity.Pages.Account.Manage.Index.cshtml , you can add entities in InputModel of Index.cshtml.cs and customize the data in OnGetAsync and OnPostAsync function .

How to Extend Roles for Multiple Locations / Sites with Asp.Net Core Identity

I have an API that is used in a multi-site/multi-location environment. At the moment, each user has roles defined but is locked to only one location. I am needing to extend this out to where a user may have admin roles for one location and then may be standard user at another location. They may also have no roles/no access to a bunch of locations.
Here is what I am working with right now (asp.net core 2.2):
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int? LocationId { get; set; }
public virtual Locations Locations { get; set; }
public int? ContactPersonId { get; set; }
public virtual ContactPerson ContactPerson { get; set; }
}
public class Locations
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ContactPerson
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<ContactOrganizationPerson> ContactOrganizationPeople { get; set; }
public virtual ICollection<ContactAddress> ContactAddresses { get; set; }
public virtual ICollection<ContactPhone> ContactPhones { get; set; }
public virtual ICollection<ContactEmail> ContactEmails { get; set; }
}
I am planning on changing the ApplicationUser to Locations table relationship to a Many to Many which would link the User to the Locations they are allowed to access. I have though about placing a payload in the M2M relationship table that would specify UserId, LocationId and Roles, but I would rather let Identity handle it if possible.
Is there a way to extend AspNetUserRoles so that I can specify a User to Role relationship for each location? Or is there a better way to accomplish this?
I'm not sure if this is going to help you, but I have extended .Net Core with functionality with IAuthorizationRequirement.
public class CustomRequirement : IAuthorizationRequirement
{
public CustomRequirement ()
{
}
}
Create a new class
public class CustomHandler : AuthorizationHandler<CustomRequirement>
Override HandleRequirementAsync
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequirement requirement)
Here you can extract info about user from DB, compare, etc. If user is not allowed, return
return Task.CompletedTask;
If user is allowed, then use
context.Succeed(requirement);
Before returning. Then in your startup.cs:
services
.AddAuthorization(options =>
{
options.AddPolicy("CustomPolicy", policy =>
policy.Requirements.Add(new CustomRequirement()));
})
And then in your controllers you can add attribute
[Authorize(Policy = "CustomPolicy", Roles = "Admin")]
If requirement is not meet, user will get 401 unauthorized, which might not be what you want.

Using Complex DataType in EF CodeFirst

this is my Model :
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public string Institute { get; set; }
public string Instructor { get; set; }
public string Duration { get; set; }
public Level Level { get; set; }
public Format Format { get; set; }
public DateTime Released { get; set; }
public string FileSize { get; set; }
public string Desciption { get; set; }
}
public enum Level
{
Beginner,
Intermediate,
Advanced
}
public enum Format
{
Avi,
Hd,
FullHd
}
public class CourseDb:DbContext
{
public DbSet<Course> Courses { get; set; }
}
when I want to Create my new Controller with Scoffolding Using EF Template,
It's not create both Level and Format fields while I am using EF5
what's my problem?
Thanks in your advise
Enum types are currently not supported when scaffolding, which is most likely why the fields are not created.
My advice would be to use a helper method such as : Working with enums in ASP.NET MVC 3
and code it manually.
Update:
Looks like there is ticket logged for the support it here: http://mvcscaffolding.codeplex.com/workitem/10