Is Identity Core 2 IdentityRole missing defintions for Users? - identity

Am I missing something or has the definition for Users been removed from IdentityRole in Identity Core 2?
I am using asp.net core 2 and I need to calculate the number of users per role. This worked just fine in Core 1 with the following standard code
public class ApplicationRoleController : Controller
{
private readonly RoleManager<ApplicationRole> roleManager;
public ApplicationRoleController(RoleManager<ApplicationRole> roleManager)
{
this.roleManager = roleManager;
}
[HttpGet]
public IActionResult Index()
{
List<ApplicationRoleListViewModel> model = new List<ApplicationRoleListViewModel>();
model = roleManager.Roles.Select(r => new
{
RoleName = r.Name,
Id = r.Id,
Description = r.Description,
NumberOfUsers = r.Users.Count
}).ToList()
.Select(r => new ApplicationRoleListViewModel
{
RoleName = r.RoleName,
Id = r.Id,
Description = r.Description,
NumberOfUsers = r.NumberOfUsers
}).ToList();
return View(model);
}
In My application using Core 2, the line NumberOfUsers = r.Users.Count, where r is derived from the class ApplicationRole with the error that "ApplicationRole does not contain a definition for Users" The ApplicationRole inherits from IdentityRole.
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
public class ApplicationRole : IdentityRole
{
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
public string IPAddress { get; set; }
}

You can use this
var admins = _userManager.GetUsersInRoleAsync("Admin").Result;
var number = admins.Count;
The issue with Core 2 apparently is that they forgo the navigation properties in
AspNetUsers AspNetUserRoles AspNetRoles. No idea why. Its very frustrating to be honest. Supposedly you can re-implement them, but so far I had no luck. I am here trying to find a way to list all users with all their roles.
I think the above code is what you need tho.
Also _userManager is imported as such in a controller
private readonly UserManager<ApplicationUser> _userManager;
public MyControllerController(DBContext context, UserManager<ApplicationUser> userManager)
{
this.context = context;
_userManager = userManager; ;
}

Related

jsonserializer.serialize library failed

public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
}
public IActionResult Index()
{
var products = new List<Product>
{
new Product{Id = 1, ProductName= "Kulaklik", Quantity = 4},
new Product{Id = 2, ProductName= "Şarj Kablosu", Quantity = 6},
new Product{Id = 3, ProductName= "Akilli Saat", Quantity = 5}
};
string data = JsonSerializer.Serialize(products);
// return View();
TempData["x"] = 5;
ViewBag.x = 5;
ViewData["x"] = 5;
return RedirectToAction("Index2");
}
public IActionResult Index2()
{
var data = TempData["products"].ToString();
List<Product> products = JsonSerializer.Deserialize<List<Product>>(data);
return View();
}
I have an Asp.Net Core Mvc project.
I want to send data to another Action with JsonSerializer class.
But among the overloads of the Serializer method there is no method that expects only a single value. I wonder what package I need to add for Visual Studio?
serialize has a red line under it
You probably have installed both - Newtonsoft.Json and System.Text.Json serializers. Newtonsoft.Json.JsonSerializer.Serialize doesnt have an overload with one argument and it causes an error. So you have to use a namespace to use anther serializer
string data = System.Text.Json.JsonSerializer.Serialize(products);

EF Core Enumeration class throwing exception

I am using an enumeration class like this:
public class BillTransactionState
{
public static readonly BillTransactionState Initialized = new BillTransactionState(1, "Initialized");
public static readonly BillTransactionState Invoiceable = new BillTransactionState(2, "Invoiceable");
public static readonly BillTransactionState NoSow = new BillTransactionState(3, "NoSow");
public static readonly BillTransactionState Invoiced = new BillTransactionState(4, "Invoiced");
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
I have another class that references BillTransactionState:
public class BillTransactionStateHistory : IEntity<long>
{
public long Id { get; set; }
public DateTime EffectiveDate { get; set; }
public BillTransactionState BillTransactionState { get; set; }
}
In my webapi, when I do something like this:
var billTransactionStateHistory = new BillTransactionStateHistory ({
BillTransaction = BillTransaction .Initialized,
EffectiveDate = DateTime.Now
});
_dbContext.BillTransactionStateHistories.AddAsync(billTransactionStateHistory)
I get an error:
Identity insert is off for BillTransactionState.
I realized EF Core is trying to insert a row in BillTransactionState table with values 1 (for Id) and 'Initliazed'. How can I stop EF Core from trying to insert a row in this enumerated class. Any help regarding this will be highly appreciated. Thank you.
Write your BillTransactionStateHistory model class as follows:
public class BillTransactionStateHistory : IEntity<long>
{
public long Id { get; set; }
public DateTime EffectiveDate { get; set; }
public int BillTransactionState { get; set; }
}
Note: After that don't forget to update the database accordingly!
Then in the Web API Method:
var billTransactionStateHistory = new BillTransactionStateHistory ()
{
BillTransactionState = BillTransactionState.Initialized.Id,
EffectiveDate = DateTime.Now
};
_dbContext.BillTransactionStateHistories.AddAsync(billTransactionStateHistory)
You can see this answer on the official EF Core GitHub repository.
Your enumeration class and entity class would remain the same. You would have to introduce a ValueConverter or use PropertyBuilder.HasConverter to provide your mappings to and from BillTransactionState and int.
Lambda example:
// builder is IEntityTypeConfiguration<BillTransactionStateHistory>
builder.Property(e => e.BillTransactionState)
.HasColumnName("state")
.HasConversion(state => state.Id, stateId => SomeLookupMethod(stateId));
public BillTransactionState SomeLookupMethod(int id)
{
// TODO: Lookup transaction state based on id.
}
Please be aware that EF Core 2.x has issues with value converters and lambdas properly mapping to query expressions. EF Core 3.x has fixed this (related issue)

Entity null - Linq to SQL

I need some help...
I have my entity that i have create manually.
public class Project()
{
public Project Data {get;set;}
public string ProjectID { get; set; }
public string AreaID { get; set; }
public string Country { get; set; }
}
Where property "Project" is the the table created by SQLmetal.
I have also created my class, with SQLmetal, wish there have there own entity.
Now i trying to parse between them in the constructor like:
public Project()
{
ProjectID = Data.ProjectID;
AreaID = Data.AreaID;
Country = Data.Country;
}
But when I use
projects.Select(p => new Project { Data = p });
the Data property in the constructor is null.
Any idea why? and how will I solve this the better way?
Yes, because the initializer
var x = new Project { Data = p };
is equivalent to
var x = new Project();
x.Data = p;
The Data property is set AFTER the constructor.
You can solve it by creating a constructor that takes Data as a parameter
public Project(Data data)
{
this.Data = Data;
ProjectID = Data.ProjectID;
AreaID = Data.AreaID;
Country = Data.Country;
}
and call the constructor
projects.Select(p => new Project(p));

JSON + LazyLoad

Guys, I'm havin a problem with this...
My User class has a property UserType userType like below:
public class User
{
public virtual int Id { get; set; }
public virtual string User { get; set; }
public virtual string Name { get; set; }
public virtual UserType userType { get; set; }
}
I can't return a JSON, like this...
[HttpGet]
public JsonResult JSONUsers(string q)
{
IEnumerable<User> model = dataServ.Users.GetUsers( q );
return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
}
I'm getting an error:
A circular reference was detected
while serializing an object of type
'System.Reflection.RuntimeModule'.
The reason I'm getting this error is the Lazy-Load (at least that's what I understood), and to poorly solve it, I did:
public JsonResult JSON(string q)
{
List<User> model = new List<User>();
IEnumerable<User> users= dataServ.Users.Getusers( q );
foreach (var item in users)
{
User user = new User
{
Id = item.Id,
Name = item.Name
};
model.Add( user );
};
return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
}
I don't think this is a good solution. In this case I only need de "Id" and "Name" properties, but what if I need all properties? Will I have to copy one by one?
Can Anybody tell me if there is a better solution?
Thanks,
Thiago
Ayende wrote a great series of blog posts about this problem.
But to summarize: USE VIEW MODELS => and by the way that's the solution to more than half of the questions on StackOverflow about ASP.NET MVC that I am answering.

Entity Framework 4.1, MVC3 JsonResult and Circular References

I'm trying to learn Entity Framework Code First development with ASP.NET MVC3.
Let's say I have a simple data Model for an Auction and Bids and I'd like to query all the Auctions and their Bids.
I have turned off LazyLoadingEnabled and ProxyCreationEnabled.
Here is the code I have:
public class MiCoreDb2Context : DbContext
{
public MiCoreDb2Context()
: base()
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Auction> Auctions { get; set; }
public DbSet<Bid> Bids { get; set; }
}
public class Auction
{
public int AuctionId { get; set; }
public virtual ICollection<Bid> Bids { get; set; }
}
public class Bid
{
public long BidId { get; set; }
public int AuctionId { get; set; }
[ForeignKeyAttribute("AuctionId")]
public virtual Auction Auction { get; set; }
}
public JsonResult Thing()
{
List<Auction> auctions;
using (var db = new MiCoreDb2Context())
{
var auctions = (from a in db.Auctions.Include("Bids") select a).ToList();
}
return Json(auctions, JsonRequestBehavior.AllowGet);
}
When I load the page, a circular reference occurs. How will I get around this?
When I load the page, a circular reference occurs. How will I get around this?
By using view models (and by the way that's the answer to any question you might have concerning ASP.NET MVC :-)). Ayende Rahien has an excellent series of blog posts on this topic.
Conclusion: absolutely always pass/take view models to/from a view. Absolutely never pass/take models (EF, domain, ...) to/from a view. Once this fundamental rule is being respected you will find out that everything works.
I solved this problem by doing a projection in the Linq to Entities query. This will create anonymous types which can be serialized to json without any circular reference issues.
var result =
from Item in dbContext.SomeEntityCollection
where SomePredicate
select new { Property1 = Item.Property1, Property2 = Item.Property2 };
Return Json(result, JsonRequestBehavior.AllowGet);
BOb