Object Reference not.... At the time of _mscustomerRepository.Insert(customer); - asp.net

I am working on Nopcommerce 2.40 .I have created new table ,its class and mapping in project
class code
namespace Nop.Core.Domain.Customers
{
public partial class MSCustomer:BaseEntity
{
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Address { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string ComapnyName { get; set; }
public virtual DateTime CreatedOnUtc { get; set; }
}
}
Below is my mapping
public partial class MSCustomerMap : EntityTypeConfiguration<MSCustomer>
{
public MSCustomerMap()
{
this.ToTable("MSCustomer");
this.HasKey(c => c.Id);
this.Property(u => u.Name).HasMaxLength(1000);
this.Property(u => u.Address).HasMaxLength(1000);
this.Property(u => u.Email).HasMaxLength(100);
this.Property(c => c.PhoneNumber).HasMaxLength(100);
this.Property(c => c.CompanyName).HasMaxLength(100);
}
}
public virtual void CreateCustomer(MSCustomer customer)
{
if (customer == null)
throw new ArgumentNullException("cutomer");
_mscustomerRepository.Insert(customer);
//event notification
_eventPublisher.EntityUpdated(customer);
}
I have created "MScustomer" table in database but at the time of insertion its throwing error that "Object reference not set to an instance of an object."
In Controller I am assigning values to property and passing customer class to insert method.
Is there any solutions.
It throws exception at the _mscustomerRepository.Insert(customer);
Thanks In Advance

Related

.NET querying Aspnetusers instead of Custom AuthUser and Yet AspNetUser does not Exist

I write a custom IdentityUser which is AuthUser.
public class AuthUser : IdentityUser
{
public int StudentsId { get; set; }
public virtual Students StudentProfile { get; set; }
public int InstructorId { get; set; }
public virtual Instructor InstructorProfile { get; set; }
public bool IsStudent { get; set; }
public bool IsInstructor { get; set; }
}
The context is okay as you can see
public class LmsContext : IdentityDbContext<AuthUser> //DbContext
{
}
The startup.cs is all setup
services.AddDbContext<LmsContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("UCIPrimarySchool"))
);
services.AddDefaultIdentity<AuthUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<LmsContext>();
services.AddControllersWithViews();
services.AddRazorPages();
But when I try to login I get the following error.
An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'AspNetUsers'.
Microsoft.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__169_0(Task<SqlDataReader> result)
Why is is not querying the extended AuthUser but instead goes for the none existing table AspNetUsers?
First, you should clarify your relationship and then migrations and updated the database correctly.
Change your AuthUser like this:
public class AuthUser : IdentityUser
{
public virtual Students StudentProfile { get; set; }
public virtual Instructor InstructorProfile { get; set; }
public bool IsStudent { get; set; }
public bool IsInstructor { get; set; }
}
In your Context:
public DbSet<Students> Students { get; set; }
public DbSet<Instructor> Instructor { get; set; }
Migration and update:
After successfully updating the database, you need to change your View/Shared/_LoginPartial code:
#inject SignInManager<IdentityUser> SignInManager
#inject UserManager<IdentityUser> UserManager
to
#inject SignInManager<AuthUser> SignInManager
#inject UserManager<AuthUser> UserManager
Then
Select your LmsContext Add
Then start your app,and login.

How to extend Application User to hold a collection of orders?

I'm trying to extend Application User (using Code-First) to hold a collection of orders, but I'm getting errors.
My Order class is
public class Order
{
public Order()
{
OrderDetails = new HashSet<OrderDetails>();
}
public int ID { get; set; }
public DateTime OrderDate { get; set; }
public string UserId { get; set; }
public bool IsDelivered { get; set; }
public bool IsReturned { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ICollection<OrderDetails> OrderDetails { get; set; }
}
And I'm trying to extend Application user like this
public class ApplicationUser : IdentityUser
{
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 string FirstName { get; set; }
public string LastName { get; set; }
public string CompanyName { get; set; }
public string Profession { get; set; }
public string TaxAuthority { get; set; }
public string TaxNumber { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
public bool NewsLetterSubscribe { get; set; } = false;
public DateTime TimeStamp { get; set; } = DateTime.Now;
public ICollection<Order> Orders { get; set; }
}
And I'm getting the following errors:
QCMS.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
QCMS.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
Can you please help me to solve this problem?
UPDATE:
I'm using two db contexts. The one provided for Individual User Account (when the project is first created) and a second one named "qvModel" that is for all other database classes of my project.
public partial class qvModel : DbContext
{
public qvModel()
: base("name=qvModel")
{
}
//APPSETTINGS
public virtual DbSet<AdminLog> AdminLog { get; set; }
public virtual DbSet<WebLog> WebLog { get; set; }
//LANGUAGES
public virtual DbSet<Language> Languages { get; set; }
.
.
.
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<OrderDetails> OrderDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Precision attribute for decimals
Precision.ConfigureModelBuilder(modelBuilder);
modelBuilder.Entity<Language>()
.HasMany(e => e.Brochures)
.WithRequired(e => e.Language)
.WillCascadeOnDelete(true);
.
.
.
modelBuilder.Entity<Order>()
.HasMany(c => c.OrderDetails)
.WithRequired(c => c.Order)
.WillCascadeOnDelete(true);
modelBuilder.Entity<ApplicationUser>()
.HasMany(c => c.Orders)
.WithRequired(c => c.User)
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
I found a solution that is very simple.
The solution is to inherit from IdentityDbContext like this
public class qvModel : IdentityDbContext<ApplicationUser>
{
public qvModel()
: base("name=qvModel")
{
}
I was also missing the following line from OnModelCreating
base.OnModelCreating(modelBuilder);
After these changes, my migration is working and I stopped getting the errors I mentioned.

Created and Modified date issue

I was practicing User.Identity and timestamps functions in ASP.NET MVC 5,
So I created a student class filled some properties, I just wanted to test if it is capturing timestamps and userId, so user id is getting captured and datetime too, problem is whenever I'm editing a record and save it, its created date becomes Null and modified date is updated, please review the code and help.
Thanks in advance.
Below is the Code
{
public class BaseEntity
{
public DateTime? DateCreated { get; set; }
public string UserCreated { get; set; }
public DateTime? DateModified { get; set; }
public string UserModified { get; set; }
}
public class Student : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Subject { get; set; }
public string Class { get; set; }
public Section Section { get; set; }
public byte SectionId { get; set; }
}
then I used Codefirst approach and created an application Database and added this code in Identity Model
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Student> Students { get; set; }
public override int SaveChanges()
{
AddTimestamps();
return base.SaveChanges();
}
//public override async Task<int> SaveChangesAsync()
//{
// AddTimestamps();
// return await base.SaveChangesAsync();
//}
private void AddTimestamps()
{
var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
var currentUsername = !string.IsNullOrEmpty(System.Web.HttpContext.Current?.User?.Identity?.Name)
? HttpContext.Current.User.Identity.Name
: "Anonymous";
foreach (var entity in entities)
{
if (entity.State == EntityState.Added)
{
((BaseEntity)entity.Entity).DateCreated = DateTime.UtcNow;
((BaseEntity)entity.Entity).UserCreated = currentUsername;
}
else
((BaseEntity)entity.Entity).DateModified = DateTime.UtcNow;
((BaseEntity)entity.Entity).UserModified = currentUsername;
}
}
public DbSet<Section> Sections { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
I have created a simple controller with create,edit and dispay actions.
The code you posted doesn't show DateCreated being set to null as far as I can see. I think the issue is when you save an existing record you do not have the DateCreated or UserCreated fields in your view. So when you post the form the MVC model binder doesn't see them and thus sets them to null (I'm assuming your are binding to the Student model in your controller action).
In your edit view add the following hidden fields:
#Html.HiddenFor(model => model.DateCreated)
#Html.HiddenFor(model => model.UserCreated)
Now when you post the form the MVC model binder will bind these values to your model and save them to the database.

AutoMapper - Cannot map between IdentityUser subclass and its correspondant DTO

I'm working on a project with asp.net core and Identity,
I am trying to create a mapping configuration between IdentityUser subclasse and its correspondant DTO using Automapper
I have done similar configuration with other classes and it works fine, but with IdentityUser subclass it behaves differently :
Here is my IdentityUser subclasse :
public partial class Collaborateur : IdentityUser
{
public Collaborateur() : base()
{
this.Activites = new HashSet<ActiviteCollaborateur>();
this.ActeursAvantVente = new HashSet<ActeurAvv>();
}
public string Nom { get; set; }
public string Prenom { get; set; }
public string Telephone { get; set; }
public Nullable<long> Matricule { get; set; }
public string Structure { get; set; }
public string Login { get; set; }
public RoleEnum Role { get; set; }
public virtual ICollection<ActiviteCollaborateur> Activites { get; set; }
public virtual ICollection<ActeurAvv> ActeursAvantVente { get; set; }
public virtual Agence Agence { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime LastModified { get; set; }
}
Its corresponding DTO :
public class CollaborateurDTO : BaseDTO
{
public string Nom { get; set; }
public string Prenom { get; set; }
public string Telephone { get; set; }
public Nullable<long> Matricule { get; set; }
public string Structure { get; set; }
public string Login { get; set; }
public RoleEnum Role { get; set; }
}
CollaborateurProfile config class :
public class CollaborateurProfile : Profile
{
CollaborateurProfile()
{
CreateMap<Collaborateur, CollaborateurDTO>().ReverseMap();
CreateMap<Collaborateur, Collaborateur>()
.ForMember(x => x.Id, opt => opt.Ignore())
.ForMember(x => x.CreatedAt, opt => opt.Ignore())
.ForMember(x => x.LastModified, opts => opts.MapFrom(src => DateTime.UtcNow));
}
}
and Startup.cs :
services.AddAutoMapper();
it stops at this line with
MissingMethodException was unhandled by user code
An exception of type 'System.MissingMethodException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code
By mistake i answered this question at the question linked in the comments (https://stackoverflow.com/a/46567611/7131186)
Here is my answer:
In my case (and it seems that this is your case too) it was a copy/paste problem. I somehow ended up with a PRIVATE constructor for my mapping profile:
using AutoMapper;
namespace Your.Namespace
{
public class MappingProfile : Profile
{
MappingProfile()
{
CreateMap<Animal, AnimalDto>();
}
}
}
(take note of the missing "public" in front of the ctor)
which compiled perfectly fine, but when AutoMapper tries to instantiate the profile it can't (of course!) find the constructor!

table already exists exception when migrate DB using Entity Framework Core and SQLite

I'm using EF Core and SQLite in UWP. I tried to migrate by calling DbContext.Database.Migrate() but I always get Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: 'table "Tags" already exists'.'.
I'm sure that the table doesn't exist because I checked on bin/debug folder, there is no database file. Even I check in wrong folder, there shouldn't have a problem doesn't it?
I've deleted Migrations folder many times but I don't think this is the cause of this exception.
This is DbContext code.
public class AppDbContext : DbContext
{
public DbSet<Word> Words { get; set; }
public DbSet<WordMeaning> WordMeanings { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<WordTag> WordTags { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=Vocabulary.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// PK declaration
modelBuilder.Entity<Word>()
.HasKey(w => w.Text);
modelBuilder.Entity<WordMeaning>()
.HasKey(wm => new { wm.WordText, wm.WordClass });
modelBuilder.Entity<Tag>()
.HasKey(t => t.Name);
modelBuilder.Entity<WordTag>()
.HasKey(wt => new { wt.WordText, wt.TagName });
// relation declaration
modelBuilder.Entity<Word>()
.HasMany(w => w.WordMeanings)
.WithOne(wm => wm.Word)
.HasForeignKey(wm => wm.WordText)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<WordTag>()
.HasOne(wt => wt.Tag)
.WithMany(t => t.WordTag)
.HasForeignKey(wt => wt.TagName);
modelBuilder.Entity<WordTag>()
.HasOne(wt => wt.Word)
.WithMany(w => w.WordTag)
.HasForeignKey(wt => wt.WordText);
}
}
and all of models code.
public class Tag
{
public string Name { get; set; }
public string Description { get; set; }
public List<WordTag> WordTag { get; set; }
}
public class Word
{
public string Text { get; set; }
public WordClass WordClasses { get; set; }
public DateTime AddedDate { get; set; }
public List<WordMeaning> WordMeanings { get; set; }
public List<WordTag> WordTag { get; set; }
}
public class WordMeaning
{
public string WordText { get; set; }
public string Definition { get; set; }
public string Example { get; set; }
public WordClass WordClass { get; set; }
public Word Word { get; set; }
}
public class WordTag
{
public Word Word { get; set; }
public Tag Tag { get; set; }
public string WordText { get; set; }
public string TagName { get; set; }
}
Do not use both EnsureCreated and Migrate, Only Migrate enough to create and migrate the DB
using (var db = new DBContext())
{
//db.Database.EnsureCreated(); Don't use
db.Database.Migrate();
}
#Gert Arnold said, Your SQLite database file (Vocabulary.db) should be created on the LocalFolder by default. You should be able to find the database with Tag table is already created on C:\Users\{username}\AppData\Local\Packages\{your app package name}\LocalState). The package name you can find by Package.appxmanifest->Packing->Package name on your project. More details about the file access on uwp app please reference Files, folders, and libraries.
And more details about entity framework with uwp please reference UWP - New Database.

Resources