Cannot use table 'AspNetRoles' for entity type 'AspNetRoles' since it is being used for entity type 'IdentityRole'
The full error message:
InvalidOperationException: Cannot use table 'AspNetRoles' for entity type 'AspNetRoles' since it is being used for entity type 'IdentityRole' and there is no relationship between their primary keys.
Each time I am trying to access the database using Entity FrameWork Core to read/write data I am getting this exception.
The code generating the exception could be as simple as
var p = _context.Platforms.Where(c=> c.PlatformId == 1);
I am using Identity and my database context is inheriting from IdentityDbContext<AspNetUsers>
I am using Entity Framework Core 2.2
See also questions close to this topic
-
getting prob on reading nested class c#
Hi really need assistance here,
I have 2 classes which i use to read from json i need to save into 2 tables (root and participants) in 1 submission. i will have only 1 root with 1 or many participants. i have no prob saving the root but i have prob reading if i am sending both (root with participants}
[ { "NoIC": "122233243", "Nama": "TEST NAME", ... "Participant": [ { "Nama" : "Participant 1", "Bil" : "1", ... }, { "Nama" : "Participant 2", "Bil" : "1", .... } ] } ] public class Participant { public string ref_no { get; set; } public string Nama { get; set; } public string Bil { get; set; } public string Price { get; set; } public string RequestedPlace { get; set; } public string RequestedExe { get; set; } public string RequestedDate { get; set; } public string Type { get; set; } } public class Root { public string NoIC { get; set; } public string Nama { get; set; } public string HPNo { get; set; } public string Email { get; set; } public string Type { get; set; } public string RegisterBy { get; set; } public List<Participant> Participant { get; set; } } public string RegisterApplication([FromBody] Root register, Participant participants) { try { using (MySqlConnection sql = new MySqlConnection(_connectionString)) { using (MySqlCommand cmd = new MySqlCommand("GetInsertApplication", sql)) { sql.Open(); cmd.CommandType = System.Data.CommandType.StoredProcedure; // cmd.Parameters.AddWithValue("@refNo", register.RefNo); cmd.Parameters.AddWithValue("@NoIC", register.NoIC); cmd.Parameters.AddWithValue("@Nama", register.Nama.ToUpper()); cmd.Parameters.AddWithValue("@NoFonHp", register.HPNo); cmd.Parameters.AddWithValue("@Email", register.Email); cmd.Parameters.AddWithValue("@refType", register.Type); cmd.Parameters.AddWithValue("@RegisterBy", register.RegisterBy); ...... ref_no = refnoParameter.Value.ToString(); //will pass this refno to child/participant
my prob is here. i need to read the child (1 Root can have more than 1 participant)
List<Participant> participants = new List<Participant>(); using (MySqlCommand cmd2 = new MySqlCommand("GetInsertParticipant", sql)) { cmd2.Parameters.AddWithValue("@ref_no", ref_no); cmd2.Parameters.AddWithValue("@Nama", participant.Nama.ToUpper()); cmd2.Parameters.AddWithValue("@Bil", participant.Bil); cmd2.Parameters.AddWithValue("@Price", participant.Price); cmd2.Parameters.AddWithValue("@RequestedPlace", participant.RequestedPlace); cmd2.Parameters.AddWithValue("@RequestedExe", participant.RequestedExe); cmd2.Parameters.AddWithValue("@RequestedDate", participant.RequestedDate); cmd2.Parameters.AddWithValue("@Type", participant.Type); cmd2.Connection.Open(); cmd2.CommandType = CommandType.Text; cmd2.ExecuteNonQuery();
}}}}}
anybody please, i stuck here for few days and i really need your help/opinion. thaks in advanced
-
How do I insert input from form to database?
My model looks like this:
public class Customer { public int CustomerId { get; set; } [Required(ErrorMessage = "Please enter a valid first name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter a valid last name")] public string LastName { get; set; } [Required(ErrorMessage = "Please enter a valid address")] public string Address { get; set; } public string Email { get; set; } [Required(ErrorMessage = "Please enter a valid city")] public string City { get; set; } public string Phone { get; set; } [Range(1, 5, ErrorMessage = "Please enter a valid country")] public int CountryId { get; set; } public Country Country { get; set; } [Required(ErrorMessage = "Please enter a valid state")] public string State { get; set; } [Required(ErrorMessage = "Please enter a valid postal code")] public string PostalCode { get; set; } public string fullname => FirstName + LastName; }
My controller looks like this:
public class CustomerController : Controller { private CustomerContext context { get; set; } public CustomerController(CustomerContext ctx) { context = ctx; } public IActionResult List() { var customers = context.Customers.ToList(); return View(customers); } [HttpGet] public IActionResult Add() { ViewBag.Action = "Add"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View("Edit", new Customer()); } [HttpGet] public IActionResult Edit(int id) { ViewBag.Action = "Edit"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); var customer = context.Customers .Include(c => c.Country) .FirstOrDefault(c => c.CustomerId == id); return View(customer); } [HttpPost] public IActionResult Edit(Customer customer) { string action = (customer.CustomerId == 0) ? "Add" : "Edit"; if (ModelState.IsValid) { if (action == "Add") { context.Customers.Add(customer); } else { context.Customers.Update(customer); } context.SaveChanges(); return RedirectToAction("List", "Customer"); } else { ViewBag.Action = action; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View(customer); } }
I also have a DbContext file with data i created to test other things:
public class CustomerContext : DbContext { public CustomerContext(DbContextOptions<CustomerContext> options) :base(options) { } public DbSet<Customer> Customers { get; set; } public DbSet<Country> Countries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Country>().HasData( new Country { CountryId = 1, Name = "Canada"}, new Country { CountryId = 2, Name = "United States"}, new Country { CountryId = 3, Name = "United Kingdom" }, new Country { CountryId = 4, Name = "Mexico" }, new Country { CountryId = 5, Name = "Russia" } ); modelBuilder.Entity<Customer>().HasData( new Customer { CustomerId = 1, FirstName = "Bruce", LastName = "Wayne", Phone = "416-123-4567", Email = "bruce.wayne@gmail.com", CountryId = 1, Address = "123 sesame street", City = "Toronto", PostalCode = "L812A", State = "Ontario" } ); }
I already did the add-migration and updated my database via the package manager console. I created a form in the view that looks like this:
Cancel<form method="post" asp-action="Add"> <div asp-validation-summary="All"> <div> <label asp-for="FirstName">First Name</label> <input type="text" name="FirstName" asp-for="FirstName" /> </div> <div> <label asp-for="LastName">Last Name</label> <input type="text" name="LastName" asp-for="LastName" /> </div> <div> <label asp-for="Address">Address</label> <input type="text" name="Address" asp-for="Address" /> </div> <div> <label asp-for="City">City</label> <input type="text" name="City" asp-for="City" /> </div> <div> <label asp-for="State">State</label> <input type="text" name="State" asp-for="State" /> </div> <div> <label asp-for="PostalCode">Postal Code</label> <input type="text" name="Postal Code" asp-for="PostalCode" /> </div> <div> <label asp-for="CountryId">Country</label> <select name="Country" asp-for="CountryId"> @foreach (Country country in ViewBag.Countries) { <option value="@country.CountryId">@country.Name</option> } </select> </div> <div> <label asp-for="Email">Email</label> <input type="text" name="Email" asp-for="Email" /> </div> <div> <label asp-for="Phone">Phone</label> <input type="text" name="Phone" asp-for="Phone" /> </div> <input type="hidden" asp-for="CustomerId" /> </div> <button type="submit" value="Save" asp-controller="Customer" asp-action="List">Save</button>
I've tried looking up multiple different solutions to solve my issue but I cant seem to figure out how to solve it. If someone could help me that would be much appreciated. thanks in advance.
-
Submit button doenst work with script asp.net mvc5
I have a maybe simple problem but I don`t have that much experience with scripts:
I have this Skript in my _Layout.cshtml:
<script> $('button').click(function () { $(this).prop('disabled', true); }); </script>
and one of my views:
@using (Html.BeginForm("Create", "Home", FormMethod.Post, null)) { @Html.AntiForgeryToken() <div class="mt-5 d-flex flex-row"> <textarea class="form-control" name="TextArea"></textarea> <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button> </div> }
This form works great without the script, but for any reason with the script it doesn`t work.
I placed the script in the _layout.cshtml because I want to have it for all buttons in my asp.net page.
After click on the button the button is disabled - as I wish - but the action result "Create" in the HomeController will not called.
I think I need to extend the script but can someone help me how to do it?
Thanks all
-
EF Core seeding user data getting duplicate role in users table warning
When I am seeding test data that I always want their I am getting the issue
The error I am getting is but why when my user and roles is empty , I am using Ef Core 5
The seed entity for entity type 'IdentityUserRole' cannot be added because another seed entity with the same key value for {'UserId', 'RoleId'} has already been added. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
public class UsersWithRolesConfig : IEntityTypeConfiguration<IdentityUserRole<string>> { private const string adminId = "B22698B8-42A2-4115-9631-1C2D1E2AC5F7"; private const string TestUser1Id = "7796F3F2-5600-40A8-99B4-832EE57DC7E1"; private const string TestUser2Id = "4F75BBA1-1CDF-44A7-84DF-D0C617E5E19D"; private const string ClubSuperAdminRole = "f95d8e54-ab12-406b-973b-ab92d4cab72a"; private const string ClubUserRole = "c2f9a56d-4e18-4d38-8eab-7a141895b049"; private const string ClubModRole = "65f1941d-048a-4b02-ad8e-1757e392aad8"; private const string Admin = "20ab180a-70cf-48b9-9315-4308b385b83f"; IdentityUserRole<string> TestUser2Roles = new IdentityUserRole<string> { RoleId = ClubUserRole, UserId = TestUser2Id, }; builder.HasData(TestUser2Roles); IdentityUserRole<string> TestUser1Roles = new IdentityUserRole<string> { RoleId = ClubModRole, UserId = TestUser1Id, }; builder.HasData(TestUser2Roles); }
Here is the data
And here you see the role are empty
And I am using
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Club>().Property(x => x.ClubId).HasDefaultValueSql("NEWID()"); modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() }); modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "ClubSuperAdmin", NormalizedName = "SuperAdmin".ToUpper() }); modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "ClubMod", NormalizedName = "ClubMod".ToUpper() }); modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "ClubUser", NormalizedName = "ClubUser".ToUpper() }); //modelBuilder.ApplyConfiguration(new AdminConfiguration()); //modelBuilder.ApplyConfiguration(new TestUser1Seeder()); //modelBuilder.ApplyConfiguration(new TestUser2Seeder()); modelBuilder.ApplyConfiguration(new UsersWithRolesConfig()); }
-
What is the correct way to implement AsNoTracking() in all entify framework core CRUD operations?
We are facing below issue when trying to perform some operation in application.
System.InvalidOperationException: The instance of entity type 'Table1' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
To fix this issue we have added below code in Add and Update operation, then things started working.
_context.Entry(item).State = EntityState.Detached;
#1. I'm not sure if this is correct way to implement AsNoTracking() in all CRUD operations.
#2. In fact some team member started reporting data got removed from some table because of EntityState.Detached, is this possible?
Complete service code:-
private readonly DataContext _context; public CartService(DataContext context) { _context = context; } public async Task<Cart> Get(string id) { return await _context.Cart.AsNoTracking().Where(i => i.Id == id).FirstOrDefaultAsync(); } public IQueryable<Cart> GetAll() { return _context.Cart.AsNoTracking(); } public async Task<Cart> Add(Cart item) { item.Timestamp = DateTime.UtcNow; item.Deleted = false; _context.Cart.Add(item); await _context.SaveChangesAsync(); _context.Entry(item).State = EntityState.Detached; // verify this return item; } public async Task<bool> Update(Cart item) { var _item = _context.Cart.Attach(item); _item.State = EntityState.Modified; await _context.SaveChangesAsync(); _context.Entry(item).State = EntityState.Detached; // verify this return true; } public async Task Remove(string id) { var item = _context.Cart.Find(id); item.Deleted = true; _context.Entry(item).State = EntityState.Modified; await _context.SaveChangesAsync(); } private bool _disposed; protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _context.Dispose(); } } _disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
-
Steeltoe Postgres connector on CloudFoundry .NET 5.0
I am using Steeltoe.CloudFoundry.Connector.EFCore with Npgsql.EntityFrameworkCore.PostgreSQL. I want to migrate the application to .NET 5.0. After updating Npgsql to 5.0.2 I am getting the error 'Unable to find DbContextOptionsBuilder, are you missing a PostgreSql EntityFramework Core assembly?' when adding DBContext.
I tried to look at the available versions of Steeltoe, but the highest NuGet I see is 2.5.2, which gives me this error as well as the older I had (2.4.4).
Is there any version combination of those libraries that works?
-
What is the best way to retrieve UserId in Entity Framework
I want to create a basic card game like Hearthstone but much much simpler :D
Basically, every user has an Inventory that contains a list of cards. I created a MyInventoryController where you should be able to retrieve your own inventory, add new Card to it and delete if you want to.
So I guess I need to get the User's id from somewhere to be sure that the new card is placed in the correct user's inventory.
As I was searching the web I couldn't find anything useful, mostly outdated stuff.
So here comes the question, how do you do it? You make a new UserRepo or something?
-
How to access other entities from ASP.NET Core Identity classes?
New to ASP.NET Core. I'm using the Identity framework for authentication, scaffolding among other the Register razor page. In the
Register.cshtml.cs
, I'd like to get data for populating a dropdown menu. The data is in another part of the Entity Framework tables. So the intention is to be able to select e.g. "Company" when registering a user.I don't like too fiddle to much with the
Register.cshtml.cs
, i.e. modifying the constructor to take my own services and/or context objects. But how to access "my own" tables from within that page?Can it be done? Or shouldn't it be done (why?)? And if not, any advice on making this general user admin stuff in combination with the Identity framework?
Thanks,
Palle
-
Is there performance impact when calling SignInManager.RefreshSignInAsync on every request
So my question is simple, will this impact performance a lot. And if it does is there a better way of doing this?
I am calling this on every request because of the following reason. Our CMS has Policy based authorization, policies are linked to roles. And we have a LOT of roles, each role is a small collection of policies so that we can "enable" features per user very specifically.
So I need to refresh the sign in because the cookies, that save the roles are not updated when I would update the database. It's also necessary to update it on the users side. Right now it works without querying the database when authorizing a policy. But it is querying the database whenever we set the new cookies, for the updates roles. My problem is that 99/100 times the roles will be the same, but we are resetting it 100/100 times.
So what is the performance impact on this, and if there is any what would be a better approach.
Link to official docs: SignInManager.RefereshSignInAsync(TUser)
I am targeting
net5.0