How to create a list page for Users in .Net Core 2 - .net-core

We extended the Identity Roles as well Users:
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AthlosifyWebArchery.Models
{
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string roleName) : base(roleName) { }
public ApplicationRole(string roleName, string description, DateTime createdDate) : base(roleName)
{
base.Name = roleName;
this.Description = description;
this.CreatedDate = createdDate;
}
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
}
}
and
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AthlosifyWebArchery.Models
{
public class ApplicationUser : IdentityUser
{
public ApplicationUser() : base() { }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Suburb { get; set; }
public string State { get; set; }
public string Postcode { get; set; }
public string Country { get; set; }
[InverseProperty("ApplicationUser")]
public IList<HostApplicationUser> HostApplicationUsers { get; set; }
[InverseProperty("HostApplicationCreatedUser")]
public HostApplicationUser HostApplicationCreatedUser { get; set; }
[InverseProperty("HostApplicationLastModifiedUser")]
public HostApplicationUser HostApplicationLastModifiedUser { get; set; }
[InverseProperty("ApplicationUser")]
public IList<ClubApplicationUser> ClubApplicationUsers { get; set; }
[InverseProperty("ClubApplicationCreatedUser")]
public ClubApplicationUser ClubApplicationCreatedUser { get; set; }
[InverseProperty("ClubApplicationLastModifiedUser")]
public ClubApplicationUser ClubApplicationLastModifiedUser { get; set; }
}
}
We are trying to create a Razor Page list of users as well their role:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using AthlosifyWebArchery.Data;
using AthlosifyWebArchery.Models;
using Microsoft.AspNetCore.Identity;
namespace AthlosifyWebArchery.Pages.Administrators.Users
{
public class IndexModel : PageModel
{
private readonly AthlosifyWebArchery.Data.ApplicationDbContext _context;
public IndexModel(AthlosifyWebArchery.Data.ApplicationDbContext context)
{
_context = context;
}
public List<ApplicationUser> User { get; private set; }
public List<IdentityUserRole<string>> UsersRoles { get; set; } // get my roles or context of user
public List<IdentityRole> AllRoles { get; private set; }
public async Task OnGetAsync()
{
User = _context.Users.Include("UserRoles").ToList();
//UsersRoles = _context.UserRoles.ToList(); // get my roles or context of user
//AllRoles = _context.Roles.ToList();
}
}
}
We managed to get just the user list BUT not sure on how to include the Roles in this case.
Any pointer please?

Firstly, try to avoid using Include function's string overload. Using the lamda instead will help you be sure that the property exists. For instance, in this case, a property named UserRoles doesn't exist for your user class in the first place. Secondly, the syntax you are trying to use it generally used for a one to many relationships. Note that users and roles is a many to many relation and the identity context (that your dbcontext extended) has a UserRoles property for this. You should be able to get all users joined with their roles using a query like this:
IEnumerable<User> users = from u in context.Users
from r in context.Roles
from ur in context.UserRoles
where u.Id == ur.UserId && ur.RoleId == r.Id
select u;

Related

create Multiple tables using Sqlite-net-pcl

I am using xamarin forms and Sqlite-net-pcl (nuget). I need help on creating multiple tables. I have set up the requirements as below. I need to do the following:
1) I need to create tables and database when the App launches. How to do this in App.cs?
Update Problem:
1) Tables are not created. Why?
---1--- in PCL : add these
-- classes for table
using SQLite;
namespace MyApp.Model
{
[Table("TblCountry")]
public class Country
{
public string Country { get; set; }
public string CountryCode { get; set; }
public string OfficialLanguage { get; set; }
}
[Table("TblEmployees")]
public class Employee
{
[PrimaryKey, AutoIncrement]
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
}
}
--- interface class
using System;
using System.Collections.Generic;
using System.Text;
using SQLite;
namespace MyApp.DataAccessHelpers
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}
---2---in Xamarin.Droid: I add this class
using SQLite;
using System.IO;
using Xamarin.Forms;
using MyApp.Droid.Implementation;
using MyApp.DataAccessHelpers;
[assembly: Xamarin.Forms.Dependency(typeof(AndroidSQLite))]
namespace MyApp.Droid.Implementation
{
class AndroidSQLite : ISQLite
{
public SQLite.SQLiteConnection GetConnection()
{
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var path = Path.Combine(documentsPath, DatabaseHelper.DbFileName);
var conn = new SQLite.SQLiteConnection(path);
return conn;
}
}
}
------- Update :
public class DatabaseHelper
{
static SQLiteConnection sqliteconnection;
public const string DbFileName = "MyDb.db3";
public DatabaseHelper()
{
try
{
sqliteconnection = DependencyService.Get<ISQLite>().GetConnection();
sqliteconnection.CreateTable<CountryModel>();
sqliteconnection.CreateTable<EmployeeModel>();
}
catch (Exception ex)
{
string strErr = ex.ToString();
}
}
public List<CountryModel> GetAllCountry()
{
return (from data in sqliteconnection.Table<CountryModel>()
select data).ToList();
}
public CountryModel GetCountryByHuNbr(string name)
{
return sqliteconnection.Table<CountryModel>().FirstOrDefault(c => c.Name == name);
}
public void DeleteAllCountry()
{
sqliteconnection.DeleteAll<CountryModel>();
}
public void DeleteCountryByid(int ID)
{
sqliteconnection.Delete<CountryModel>(ID);
}
public void InsertCountry(CountryModel country)
{
sqliteconnection.Insert(country);
}
public void UpdateCountry(CountryModel country)
{
sqliteconnection.Update(country);
}
//------- CRUD for employee
public void InsertEmployee(EmployeeModel employee)
{
sqliteconnection.Insert(employee);
}
.....
... and all the CRUD for employee
}
}
Thanks in advance.
I created a helper class which contains all methods I need in order to interact with SQLite Database. I use the CreateTable() to create a table.
In App.xaml.cs file, I create an instance of my DataAccess helper class and I call the CreateLocalDbTables() method.
DataAccessHelper
public class DataAccess : IDisposable
{
private SQLiteConnection Connection;
#region Constructor
public DataAccess(ISQLitePlatform sQLitePlatform, string dbPath)
{
this.Connection = new SQLiteConnection(sQLitePlatform, dbPath);
}
#endregion
#region Methods
public void CreateLocaldbTables()
{
this.Connection.CreateTable<Registration>();
this.Connection.CreateTable<TransmissionLog>();
this.Connection.CreateTable<Parameters>();
this.Connection.CreateTable<Guest>();
}
In APP.xaml.cs
public partial class App : Application
{
#region Properties
public static DataAccess DBConnection { get; set; }
#endregion
public App(string localDbPath, ISQLitePlatform sqlitePlatform)
{
InitializeComponent();
DBConnection = new DataAccess(sqlitePlatform,localDbPath);
DBConnection.CreateLocaldbTables();
Model
namespace AppRegistration.Models
{
using SQLite;
using System;
[Table("Activity")]
public class Actividad
{
[Column("IdActivity")]
[PrimaryKey, Autoincrement]
public int IdActivity { get; set; }
[Column("IdEvent")]
[PrimaryKey]
public int IdEvent { get; set; }
[Column("ActivityDescription")]
[NotNull]
public string ActivityDescription { get; set; }
[Column("Status")]
[NotNull]
public string Status { get; set; }
[Column("UserId")]
[NotNull]
public int UserId { get; set; }
}
}

ASP.NET MVC 4 - Create a ViewModel from a base class (Model)

There is a class (Model) User.cs:
namespace BookStore
{
using System;
using System.Collections.Generic;
public class User
{
public int user_id { get; set; }
public string user_login_name { get; set; }
public string user_first_name { get; set; }
public string user_last_name { get; set; }
}
}
I want to create a ViewModel to then use it in Views. How should I do it? I create ViewModels folder in the project, create a class UserViewModel.cs in it, then what? I just copy and paste the original User.cs content and put limitations? Like this:
namespace BookStore.Models
{
public class UserViewModel
{
[Editable(false)]
public int user_id { get; private set; }
public string user_login_name { get; set; }
public string user_first_name { get; set; }
public string user_last_name { get; set; }
}
}
I did so and now my UserController says it can't implicitly convert type BookStore.User to BookStore.UserViewModel:
public class UserController : Controller
{
private DBEntities db = new DBEntities();
public ActionResult UserDetails()
{
UserViewModel user = db.Users.FirstOrDefault(u => u.user_login_name==User.Identity.Name);
if (user == null)
return RedirectToAction("Create");
else
return View(user);
}
I know it is important in MVC to separate concerns, domain models and view models should be used for different purposes, but why is there no any detailed info on how to create ViewModels correctly?

add-migration not generating anything

So I've tried running "add-migration AddBooking -verbose"
To this class:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace HostelBookingSystem.Models
{
public class Booking
{
[Key]
public Int32 BookingId { get; set; }
public Int32 Duration { get; set; }
public Double Price { get; set; }
public BookingStatus Status { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual Bunk Bunk { get; set; }
public virtual Room RoomPreference { get; set; }
}
}
However I'm receiving completely empty Up() and Down() methods.
The same thing happens when I remove the 3 public virtual attributes as well.
Can any explain why this is?
1) The DBContext class needs to be set up
2) Include the property for the above class in the DBContext
public DbSet<Booking> Books { get; set; }
The reason this didn't generate anything was because I didn't have a DbContext set up for the class I wished to generate a table for.

ASP.NET Mvc3/VS2010 error: An item with the same key has already been added

I've been trying to add a Controller in my Project, but I've been getting the error
An item with the same key has already been added.
while doing so.
I'm still a beginner at this, so I might have not noticed something, but I don't see any duplicate keys in my model.This is my database's diagram to get the general idea of what I'm trying to do:
I'm using Applications as the Model Class and ApplicationServices as the data Context Class while trying to create my ApplicationController and getting the error
An item with the same key has already been added.
Any ideas what I might be doing wrong?
The models I've created are the following:
Entity.cs:
using Microsoft.VisualBasic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.ComponentModel.DataAnnotations;
namespace PostGraduate.Models
{
public class ApplicationServices : DbContext
{
public DbSet<Application.Users> Users { get; set; }
public DbSet<Application.Addresses> Addresses { get; set; }
public DbSet<Application.Applications> Applications { get; set; }
public DbSet<Application.ForeignLanguages> ForeignLanguages { get; set; }
public DbSet<Application.Gmat> Gmat { get; set; }
public DbSet<Application.PostGradStudies> PostGradStudies { get; set; }
public DbSet<Application.PreGradStudies> PreGradStudies { get; set; }
public DbSet<Application.Schoolarships> Schoolarships { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Application.Users>().HasKey(a => a.UserId);
modelBuilder.Entity<Application.Addresses>().HasKey(a => a.Addresses_Id);
modelBuilder.Entity<Application.Applications>().HasKey(a => a.Applications_Id);
modelBuilder.Entity<Application.Applications>().Property(a => a.Applications_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.ForeignLanguages>().HasKey(a => a.ForeignLanguages_Id);
modelBuilder.Entity<Application.Gmat>().HasKey(a => a.Gmat_Id);
modelBuilder.Entity<Application.Gmat>().Property(a => a.Gmat_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.PostGradStudies>().HasKey(a => a.PostGradStudies_Id);
modelBuilder.Entity<Application.PostGradStudies>().Property(a => a.PostGradStudies_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.PreGradStudies>().HasKey(a => a.PreGradStudies_Id);
modelBuilder.Entity<Application.Schoolarships>().HasKey(a => a.Schoolarships_Id);
modelBuilder.Entity<Application.Schoolarships>().Property(a => a.Schoolarships_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Application.Users>().HasRequired(a => a.Applications).WithRequiredPrincipal(i => i.Users);
modelBuilder.Entity<Application.Applications>().HasMany(a => a.Addresses).WithRequired(i => i.Applications).HasForeignKey(i => i.Application_Id);
modelBuilder.Entity<Application.Applications>().HasMany(a => a.ForeignLanguages).WithRequired(i => i.Applications).HasForeignKey(i => i.Application_Id);
modelBuilder.Entity<Application.Applications>().HasOptional(a => a.Gmat).WithRequired(i => i.Applications);
modelBuilder.Entity<Application.Applications>().HasOptional(a => a.PostGradStudies).WithRequired(i => i.Applications);
modelBuilder.Entity<Application.Applications>().HasMany(a => a.PreGradStudies).WithRequired(i => i.Applications).HasForeignKey(i => i.Application_Id);
modelBuilder.Entity<Application.Applications>().HasOptional(a => a.Schoolarships).WithRequired(i => i.Applications);
}
}
}
Applications.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Applications
{
public Applications()
{
this.Addresses = new HashSet<Addresses>();
this.PreGradStudies = new HashSet<PreGradStudies>();
this.ForeignLanguages = new HashSet<ForeignLanguages>();
}
internal void BuildAddress(int p)
{
for (int i = 0; i < p; i++)
{
Addresses.Add(new Addresses());
}
}
internal void BuildPreGradStudies (int p)
{
for (int i = 0; i < p; i++)
{
PreGradStudies.Add(new PreGradStudies());
}
}
internal void BuildForeignLanguages(int p)
{
for (int i = 0; i < p; i++)
{
ForeignLanguages.Add(new ForeignLanguages());
}
}
public virtual Users Users { get; set; }
public virtual Gmat Gmat { get; set; }
public virtual PostGradStudies PostGradStudies { get; set; }
public virtual Schoolarships Schoolarships { get; set; }
public virtual ICollection<Addresses> Addresses { get; set; }
public virtual ICollection<PreGradStudies> PreGradStudies { get; set; }
public virtual ICollection<ForeignLanguages> ForeignLanguages { get; set; }
[ScaffoldColumn(false)]
public string Applications_Id { get; set; }
[ScaffoldColumn(false)]
public DateTime ApplicationDate { get; set; }
[Required]
public string FathersName { get; set; }
[Required]
public DateTime? Birthdate { get; set; }
[Required]
public string Birthplace { get; set; }
[Required]
public string Identification { get; set; }
[Required]
public string Country { get; set; }
[Required]
public string MobileNumber { get; set; }
[Required]
public string Profession { get; set; }
public string Activity { get; set; }
public string PostGradExtra { get; set; }
public string PostGradReapplication { get; set; }
public string ExtraInformation { get; set; }
[Required]
public string PostGradSource { get; set; }
}
}
Addresses.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Addresses
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string Addresses_Id { get; set; }
[ScaffoldColumn(false)]
public string Application_Id { get; set; }
[Required]
public string StreetAddress { get; set; }
[Required]
public string City { get; set; }
[Required]
public string PostalCode { get; set; }
[Required]
public string PhoneNumber { get; set; }
}
}
ForeignLanguages.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class ForeignLanguages
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string ForeignLanguages_Id { get; set; }
[ScaffoldColumn(false)]
public string Application_Id { get; set; }
public string Language { get; set; }
public string LanguageDegree { get; set; }
public string Admission { get; set; }
public bool Delete { get; set; }
}
}
Gmat.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Gmat
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string Gmat_Id { get; set; }
public DateTime? GmatDate { get; set; }
public string GmatGrade { get; set; }
}
}
PostGradStudies.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class PostGradStudies
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string PostGradStudies_Id { get; set; }
public string Aei { get; set; }
public string PostGradTitle { get; set; }
public string PostGradLength { get; set; }
public string PostGradGrade { get; set; }
public string PostGradProject { get; set; }
public string PostGradProjectGrade { get; set; }
}
}
PreGradStudies.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class PreGradStudies
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string PreGradStudies_Id { get; set; }
[ScaffoldColumn(false)]
public string Application_Id { get; set; }
public string University { get; set; }
public string Department { get; set; }
public string Admission { get; set; }
public string Graduation { get; set; }
public string DegreeGrade { get; set; }
public string ThesisSubject { get; set; }
public string ThesisGrade { get; set; }
public bool Delete { get; set; }
}
}
Schoolarships.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Schoolarships
{
public virtual Applications Applications { get; set; }
[ScaffoldColumn(false)]
public string Schoolarships_Id { get; set; }
public string Schoolar { get; set; }
public string SchoolarshipProfession { get; set; }
public string SchoolarshipInstitution { get; set; }
}
}
Users.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PostGraduate.Models.Application
{
public class Users
{
public virtual Applications Applications { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
}
Could you include your Application Controller code also?
But I suspect, that it could be because some of your entities are defined as not having autogenerated Primary Keys, that when they the objects are created, that they will all have the same key.
I would assume all the keys are set as either empty strings or NULL, so when checking for something else with a key of NULL, it would already get a match...
(sorry I don't have the best understanding of EF, but just a thought!)
One of the reason this could happen is if you have the same property twice from your view models. For example, if you have UserName on a class and you have it on another class and both are present in your view. That would create a duplicate UserName key.
I experienced this when I had two properties with the same name in one class. One a public field member and the other a get/set accessor
public class User
{
public string userName; // <---- this should be private
public string UserName
{
get { return userName; }
set { userName = value; }
}
}
Notice C# didn't complain because of case-sensitivity. I solved that by making the field variable private

Scaffolding model with inheritance in ASP.NET MVC 3 and Entity Framework

I'm trying out the new scaffolding features in MVC 3, using Entity Framework Code First. My model looks like this:
public abstract class A
{
public int Id { get; set; }
}
public class B : A
{
public string Name { get; set; }
}
public class MyContext : DbContext
{
public DbSet<A> As { get; set; }
}
I create a new controller using the new controller wizard in MVC and select to scaffold type A. CRUD code is generated and I can successfully start the project in a webbrowser. When I try to create a new A, I get the following error message:
"Cannot create an abstract class"
which makes sense. A is abstract.
Can I use scaffolding to create B's and other inherited classes from A?
AFAIK you should add a
using System.ComponentModel.DataAnnotations;
[Table("TableNameForB")]
public class B : A
{
public string Name { get; set; }
}
as attribute for your concrete class
Find here a complete example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace ZooLabPoco
{
public class Context : DbContext
{
public DbSet<Animal> Animals { get; set; }
public DbSet<Zoo> Zoos { get; set; }
}
public class Zoo
{
public int Id { get; set; }
public virtual ICollection<Animal> Animals { get; set; }
public Zoo()
{
this.Animals = new List<Animal>();
}
}
public abstract class Animal
{
public int Id { get; set; }
public int ZooId { get; set; }
public virtual Zoo Zoo { get; set; }
}
[Table("Lions")]
public class Lions : Animal
{
public string LionName { get; set; }
}
[Table("Tigers")]
public class Tigers : Animal
{
public string TigerName { get; set; }
public int TailLength { get; set; }
}
class Program
{
static void Main(string[] args)
{
var context = new Context();
context.Database.Delete();
context.Database.CreateIfNotExists();
var zoo = new Zoo();
zoo.Animals.Add(new Lions { LionName = "Fritz" });
zoo.Animals.Add(new Lions { LionName = "Jerry" });
zoo.Animals.Add(new Tigers { TigerName = "Pluto" });
context.Zoos.Add(zoo);
context.SaveChanges();
}
}
}

Resources