How to fix 'model code generator' in asp.net mvc 5 - asp.net-mvc-5

I modelling a simple library management system that able to register user and the user can issue a book.
I want the asp.net IdentityUser to create one -to many relationShip with BookIssue Custom table. because I am new to asp.net mvc 5, I can not fix the problem please help me.
public class ApplicationUser : IdentityUser
{
public virtual ICollection<BookIssue> BookIssues { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Book> Books { get; set; }
public DbSet<BookIssue> BookIssues { get; set; }
public DbSet<Catagory> Catagories { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BookIssue>()
.HasRequired(n => n.ApplicationUser)
.WithMany(a => a.BookIssues)
.HasForeignKey(n => n.ApplicationUserId)
.WillCascadeOnDelete(false);
}
}
}
BookIssue Model:
public int BookIssueId { get; set; }
public int BookId { get; set; }
public int ApplicationUserId { get; set; }
public string Email { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public virtual Book Book { get; set; }
public virtual ApplicationUser ApplicationUser { get; set;
The generated error:
There was an error running the selected code generator. 'Unable to
retrieve metadata for Librart.Models.BookIssuee'.One or more
validation errors were detected during model generation:
Library.Models.IdentityUserLogin: EntityType 'IdentityUserRole' has no
key defined.Define the key for this EntityType.
Library.Models.IdentityUserRole: EntityType 'IdentityUserLogin' has no
key defined.Define the key for this EntityType.
And many other errors are generated.

Related

Object reference not set to an instance of an object in Entity Framework

I got question on this error which I cannot solve. I am using Entity Framework database first. And before that I have deleted the entity model and create a new one. I am not sure it will affect or not.
This is my viewModel
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MVCTutorial.Models
{
public class OtherIncViewModel
{
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<UserGroup> UserGroups { get; set; }
public virtual DbSet<Patient> Patients { get; set; }
//User
public int UserId { get; set; }
public string UserFullName { get; set; }
public string UserIC { get; set; }
[DataType(DataType.Password)]
[Required(ErrorMessage = "This field is requiered.")]
public string UserPassword { get; set; }
public string UserEmail { get; set; }
public Nullable<int> UserGroupId { get; set; }
public string UserMMCRegistrationNo { get; set; }
[DisplayName("UserName")]
[Required(ErrorMessage = "This field is requiered.")]
public string UserLogin { get; set; }
public string UserFaxNo { get; set; }
public string UserDesignation { get; set; }
public string UserStatus { get; set; }
public string UserContact { get; set; }
public virtual UserGroup UserGroup { get; set; }
public string LoginErrorMessage { get; set; }
//Patient
public int PatientId { get; set; }
public string PatientName { get; set; }
public string PatientIC { get; set; }
public int PatientAge { get; set; }
public string PatientGender { get; set; }
public string Hospital { get; set; }
public string Ward { get; set; }
public string Department { get; set; }
public string Barcode { get; set; }
public string Race { get; set; }
public string PatientErrorMessage { get; set; }
public virtual ICollection<CaseOtherInc> CaseOtherIncs { get; set; }
public virtual ICollection<DraftCaseOtherInc> DraftCaseOtherIncs { get; set; }
}
}
This is my controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTutorial.Models;
namespace MVCTutorial.Controllers
{
public class WardStaffController : Controller
{
OtherIncContext db = new OtherIncContext();
// GET: WardStaff
public ActionResult Index() //Ward Staff Inbox
{
return View();
}
public ActionResult CreateTransfusion() //Ward Staff Create Transfusion
{
return View();
}
public ActionResult CreateIBCT() //Ward Staff Create IBCT
{
return View();
}
public ActionResult CreateNearMiss() //Ward Staff Create Near Miss
{
return View();
}
[HttpPost]
public ActionResult SearchPatient(MVCTutorial.Models.OtherIncViewModel patient)
{
using (OtherIncContext db = new OtherIncContext())
{ //I am wondering here why my local variable does not reference the namespace in this case is MVCTutorial. Is this why i get the null exception? I have check my database...i didn't have null record.
var patientDetails = db.Patients.Where(x => x.PatientIC == patient.PatientIC).FirstOrDefault();
if (patientDetails == null)
{
patient.PatientErrorMessage = "Please enter patient's IC number.";
return View("CreateOtherIncident", patient);
}
else
{
Session["PatientName"] = patientDetails.PatientName;
}
return RedirectToAction("CreateOtherIncident", "WardStaff");
}
}
This is my view
#model MVCTutorial.Models.OtherIncViewModel
#{
ViewBag.Title = "CreateOtherIncident";
Layout = "~/Views/Shared/_LayoutWardStaff.cshtml";
}
<h2>CreateOtherIncident</h2>
<h2>Reported By:</h2>
<p> Name: #Session["UserFullName"].ToString()</p>
<p>Email Address: #Session["UserEmail"].ToString()</p>
<p>Date:</p>
<p>Designation No.: #Session["UserDesignation"].ToString()</p>
<p>Tel.No: #Session["UserContact"].ToString()</p>
<p>Fax.No: #Session["UserFaxNo"].ToString()</p>
<h2>Patient Details:</h2>
#Html.LabelFor(model=>model.PatientIC)
#Html.EditorFor(model=>model.PatientIC)
<p>Patient Name: #Session["PatientName"].ToString()</p> //I get the exception here.
I suspect it is because of the local variable, but I cannot find any further error or exception on that.
Before the exception, To check session should not be null.
like:
#if (HttpContext.Current.Session["PatientName"] != null)
{ //#Session["PatientName"].ToString()
}

How to give a Table name in Entity Framework by code first approach in .Net Framework 4.0?

In .NET 4.0 framework the System.ComponentModel.DataAnnotations.Schema doesn't work or doesn't support I think.
I am using a code-first approach and my database already exists, and also not using ADO.net Entity Data Model.
I already used the [Table] attribute and DatabaseGenerated attribute, it's not working causing a compilation error to occur.
This is my code:
Entity class:
public class myclass
{
public myclass()
{
//
// TODO: Add constructor logic here
//
}
[Key]
public int RECORDID { get; set; }
public string AA { get; set; }
public string CAT { get; set; }
public string CS { get; set; }
public int? FS { get; set; }
public int? CA { get; set; }
public int? DR { get; set; }
public int? UM { get; set; }
public int? ID { get; set; }
public double LAT { get; set; }
public double LON { get; set; }
public int? NIC { get; set; }
}
DbContext class:
public class classContext : DbContext
{
public classContext() : base("name=DBConnection")
{
//Disable initializer
Database.SetInitializer<classContext>(null);
}
public DbSet<myclass> myclasses { get; set; }
}
Or I have to add this override method of model creating, is it helpful or not?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<myclass>().ToTable("Datatbl");
}
Help me out. Thanks
You can Use Table attribute over your class:
[Table("Datatbl")]
public class myclass
{
}

how do i use AutoMapper in ICollation<> Fields

when i use AutoMapper for mapping my ViewModels and get All News, thrown error for me.
Errors...
The following property on Mosque.Core.ViewModels.CategoryViewModel cannot be mapped:
Categories
Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type Mosque.Core.ViewModels.CategoryViewModel.
please help me, thank you
//Models
public class News
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual User User { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<News> News { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<News> News { get; set; }
}
//ViewModels
public class NewsViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<CategoryViewModel> Categories { get; set; }
public virtual UserViewModel User { get; set; }
}
public class CategoryViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<NewsViewModel> News { get; set; }
}
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<NewsViewModel> News { get; set; }
}
how do i use for select All News?
--Update1--
I used onion architecture in the project and i installed AutoMapper in the Service layer and i want get all news from repository and fill into ViewModels and pass to the UI.
my code in service layer is...
public List<NewsViewModel> GetAll()
{
Mapper.CreateMap<News, NewsViewModel>()
.ForMember(dest => dest.Categories, src => src.MapFrom(p => p.Categories))
.ForMember(dest => dest.User, src => src.MapFrom(p => p.User));
Mapper.AssertConfigurationIsValid();
var viewModels = new List<NewsViewModel>();
foreach (var item in _newsRepository.GetAll())
{
var viewModel = Mapper.Map<News, NewsViewModel>(item);
viewModels.Add(viewModel);
}
return viewModels;
}
You don't seem to have created maps for Catagory and User.
Add the following maps:
Mapper.CreateMap<User, UserViewModel>();
Mapper.CreateMap<Category, CategoryViewModel>();
By the way, why are you creating the maps inside the GetAll method? You can create the maps once, usually at application startup.

Merge ApplicationDbContext and DataContext into a single context

I am having a problem merging these 2 contexts.
I deleted this line of code from IdentityModels.cs:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
I implemented this inside my DataContext.cs
public class DataContext : DbContext
{
public DataContext()
: base("name=DefaultConnection")
{
}
// Account tables
public DbSet ApplicationUsers { get; set; }
public DbSet Roles { get; set; }
public DbSet Tokens { get; set; }
public DbSet UserClaims { get; set; }
public DbSet UserLogins { get; set; }
public DbSet UserManagements { get; set; }
public DbSet UserRoles { get; set; }
public DbSet UserSecrets { get; set; }
// App Models
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Students { get; set; }
}
Problem:
When I "update-database" it only created the Courses and Students tables.
Question
If I successfully implement this method will I lose all of the nice methods that IdentityDbContext interface offers for example:
var rm = new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(new ApplicationDbContext()));
return rm.RoleExists(name);
Ok here is the solution that I found posted by Olav Nybo in this topic How can one put application users in the same context as the rest of the objects?.
Go to his sample project on github: https://github.com/onybo/Asp.Net-Identity-sample-app/tree/master/CustomUser/CustomUser
Download the configurations folder from the Models folder and place the folder inside your models folder.
Inside your DataContext file you will put this snippet of code which will call these configuration files to build out your database.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
throw new ArgumentNullException("modelBuilder");
modelBuilder.Configurations.AddFromAssembly(typeof(Generic_Repo_Template.Models.Configurations.ApplicationUserConfiguration).Assembly);
}
Now that your database is created you still do not have access to these tables through the datacontext object. In order to be able to access these tables through your datacontext is to include these lines of code:
public virtual IDbSet<ApplicationUser> Users { get; set; }
public virtual IDbSet<IdentityRole> Roles { get; set; }
public virtual IDbSet<IdentityUserClaim> Claims { get; set; }
So the full DataContext file will look something like this:
public class DataContext : DbContext
{
public DataContext()
: base("name=DefaultConnection")
{
}
// Account tables
public virtual IDbSet<ApplicationUser> Users { get; set; }
public virtual IDbSet<IdentityRole> Roles { get; set; }
public virtual IDbSet<IdentityUserClaim> Claims { get; set; }
// App Models
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
throw new ArgumentNullException("modelBuilder");
modelBuilder.Configurations.AddFromAssembly(typeof(AspNetRoleBasedSecurity.Models.Configurations.ApplicationUserConfiguration).Assembly);
}
}
You have to use:
DbSet<Model> Name {get;set;}
Instead of
DbSet Model {get;set;}
As the answer to your question. The RoleStore needs a DbContext (IdentityDbContext inherits from DbContext). So you should be able to still use the roleManager and more...

Using Entity Framework 5.0 map relationship between parent and children when ID are Guids with newsequentialid()

I have two classes with a one to many relationship.
public partial class Client
{
public Client()
{
this.Client_Local = new HashSet<Client_Local>();
}
public System.Guid Guid { get; set; }
public string Name { get; set; }
public virtual ICollection<Client_Local> Client_Local { get; set; }
}
public partial class Client_Local
{
public System.Guid LocalGuid { get; set; }
public System.Guid Guid { get; set; }
public string CultureID { get; set; }
public string LocalName { get; set; }
public virtual Client Client { get; set; }
}
The mapping classes are:
class ClientMapping : EntityTypeConfiguration<Client>
{
public ClientMapping()
{
this.HasKey(entity => entity.Guid); //As newsequentialid()
this.ToTable("Client");
this.Property(entity => entity.Guid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
class Client_LocalMapping : EntityTypeConfiguration<Client_Local>
{
public Client_LocalMapping()
{
this.HasKey(entity => entity.LocalGuid); // as As newsequentialid()
this.ToTable("Client_Local");
this.Property(entity => entity.LocalGuid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasRequired<Client>(e => e.Client).WithMany(p => p.Client_Locals).HasForeignKey<Guid>(c => c.Guid);
}
}
I can create new instances of client class and save them to the database successfully. But when I try and add a Client_Local class and save it to the database I get "A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Guid'.".
The key fields are generated in sql as newsequentialid for performance reasons. And there is a foreign key relationship between Client_Local.Guid and Client.Guid.
Retrieving data from the database works with the above mapping classes. Any help would be greatly appreciated.

Resources