I created a database using using EF Code-first Migrations approach. When I ran the application I registered a user and expected that the identity tables be added to the database I created but I couldn't find the tables. I checked my connection string to be sure it is rightly set. Please what could I have missed out? Please help.
Edit:
This is the code for the context.
public class AppDataContext : DbContext
{
public AppDataContext()
: base("AppConnection")
{ }
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<Attendance> Attendances { get; set; }
public DbSet<ClassInfo> Classes { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<MessageBoard> MessageBoards { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<Notification_User> UserNotifications { get; set; }
public DbSet<NotificationType> NotificationTypes { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<ParentSubscription> ParentSubscriptions { get; set; }
public DbSet<PrivateMessage> PrivateMessages { get; set; }
public DbSet<School> Schools { get; set; }
public DbSet<SessionPeriod> SessionPeriods { get; set; }
public DbSet<Setting> Settings { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<TeacherSchool> TeacherSchools { get; set; }
public DbSet<Term> Terms { get; set; }
public DbSet<Work> Works { get; set; }
public DbSet<WorkType> WorkTypes { get; set; }
#region Override Methods
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Subject>()
.HasMany(c => c.Teachers).WithMany(i => i.Subjects)
.Map(t => t.MapLeftKey("SubjectID")
.MapRightKey("TeacherID")
.ToTable("SubjectTeacher"));
modelBuilder.Entity<ClassInfo>()
.HasMany(s => s.Subjects).WithMany(c => c.Classes)
.Map(u => u.MapLeftKey("ClassInfoID").MapRightKey("SubjectID").ToTable("ClassSubject"));
//modelBuilder.Entity<Department>().MapToStoredProcedures();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//modelBuilder.Entity<ClassInfo>()
// .Property(f => f.DateAdded)
// .HasColumnType("datetime2");
}
#endregion
}
When you registered a user :
Refresh your project
Show all files
You will find:
Edit:
IdentityModels.cs:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
//: base("DefaultConnection", throwIfV1Schema: false)
: base("AppConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class AppDataContext : DbContext
{
public AppDataContext()
: base("AppConnection")
{ }
}
Web.config:
<connectionStrings>
<add name="AppConnection" connectionString="Data Source=.; Initial Catalog=SIS_DB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Related
I Can't use WithMany for many-to-many connection. I tried everything, and I have not idea what tha problem it could be. Please help if you have some axperience about it.
I have two models "Drink" and "DrinkCategory". every drink could have many categories, so I need many-to-many relationship.
Here is first model "Drink":
public class Drink
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[Required]
public int DrinkId { get; set; }
[Required]
public int DrinkIngredientId { get; set; }
public string DrinkName { get; set; }
public virtual DrinkIngredient DrinkIngredients { get; set; }
public virtual ICollection<DrinkCategory> DrinkCategories { get; set; }
}
It is second model "DrinkCategorie":
public class DrinkCategory
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[Required]
public int DrinkCategoryId { get; set; }
public string DrinkCategoryName { get; set; }
public int? ParentDrinkCategoryId { get; set; }
public virtual ICollection<Drink> Drinks { get; set; }
}
Here is my DBContext:
public class EatAndDrinkDbContext : DbContext
{
public EatAndDrinkDbContext(DbContextOptions<EatAndDrinkDbContext> options) : base(options) { }
public EatAndDrinkDbContext() { }
public DbSet<Drink> Drinks { get; set; }
public DbSet<DrinkCategory> DrinkCategories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Drink>()
.HasMany(c => c.DrinkCategories)
.WithMany(i => i.Drinks)
.Map(t => t.MapLeftKey("DrinkId")
.MapRightKey("DrinkCategoryId")
.ToTable("DrinkDrinkCategory"));
base.OnModelCreating(modelBuilder);
}
}
I don't know what I am doing wrong, trying very hard to setup a database project, and keep getting errors related to the connectionstring dbcontext.
I have one applicationdbcontext which is just connecting to localdb
the problem is my other dbcontext which is where my data is seems to be in the wrong place and I am not sure how to fix it. This code is in my models folder
public DbSet<Customer> Customers { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Staff> Staff { get; set; }
public DbSet<RequestType> RequestType { get; set; }
public DbSet<CustomerJob> CustomerJobs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Customers;Trusted_Connection=True;");
}
in startup.cs I have this code..
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("ProdConnection")));
in my appsettings config I have this code..
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BRSCRM;Trusted_Connection=True;MultipleActiveResultSets=true",
"ProdConnection": "Server=(localdb\\mssqllocaldb;Database=Customers;Trusted_Connection=True;MultipleActiveResults=true"
},
yet when I run my project I get an error that the configuration being supplied is not being used,DI inversion of control indeed, its a bag of cats and its on fire!
You should remove the optionsBuilder.UseSqlServer("... line in your OnConfiguring method.
Then add a constructor to your DbContext class like this;
public YourDbContext(DbContextOptions<YourDbContext> options) : base(options)
{
}
Adding DbContext class..
public class CustomerContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Staff> Staff { get; set; }
public DbSet<RequestType> RequestType { get; set; }
public DbSet<CustomerJob> CustomerJobs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Customers;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//modelBuilder.Entity<CustomerJob>()
// .HasKey(c => new { c.JobId, c.CustomerId });
//code to require a staff member be assigned..
// modelBuilder.Entity<Staff>().Property(s => s.Name).IsRequired();
// modelBuilder.Entity<Customer>().Property(c => c.AssignedStaff).IsRequired();
}
}
public class CustomerJob
{
public int CustomerJobId { get; set; }
public int CustomerId { get; set; }
public DateTime RequestDate { get; set; }
public int JobId { get; set; }
public Job Job { get; set; }
}
public class Job
{
public int JobId { get; set; }
public int CustomerId { get; set; }
public string BusinessName { get; set; }
public string Name { get; set; }
public string JobDescription { get; set; }
public string ServiceType { get; set; }
public string GoogleLink { get; set; }
public string PoisLink { get; set; }
public bool EquisRendered { get; set; }
public bool NadirsRemoved { get; set; }
public string FolderLink { get; set; }
public string ReviewPosted { get; set; }
public string Ingestion { get; set; }
public string Moderated { get; set; }
public bool Delivered { get; set; }
public string CustomerReview { get; set; }
public string PublishedLink { get; set; }
public DateTime RequestDate { get; set; }
public DateTime LastModifiedDate { get; set; }
public DateTime ScheduleShootDate { get; set; }
public DateTime CompletionDate { get; set; }
public List<CustomerJob> CustomerJobs { get; set; }
public Staff AssignedStaff { get; set; }
}
public class Staff
{
public int StaffId { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string EMail { get; set; }
}
public class Order
{
public int OrderID { get; set; }
public int CustomerID { get; set; }
public int Order_Detail_Id { get; set; }
public List<Job> Job { get; set; }
}
public class RequestType
{
public int ID { get; set; }
public string Description { get; set; }
}
}
Startup.cs class..
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<CustomerContext>();
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
// Add Oauth Options
/* Third Party Login Authenticaton Options Google */
services.AddAuthentication().AddGoogle(googleOptions =>
{
googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});
/* End Google Options */
/* Begin Facebook Options */
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
/* End Facebook Options */
/* Begin Microsoft Options */
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:Password"];
});
/* End Microsoft Options */
/* Twitter Options */
services.AddAuthentication().AddTwitter(twitterOptions =>
{
twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
});
/* End Twitter Options */
/* Begin Identity Options Configuration */
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
}
Anyways its working now, my mistake was that I had defined the connection in 2 seperate places and I guess that threw an exception.
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!
I have got my application up and running using Code first, I am trying to set a 1-1 relationship but when I update-database I get the error "SupplyPointId: Name: Each property name in a type must be unique. Property name 'SupplyPointId' is already defined."
I've tried removing the existing index constraint on SupplyPointAddress.SupplyPointId and that does not help. In the other table its the PK. Any comments really appreciated
public partial class SupplyPoint
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointId { get; set; }
public string SPID { get; set; }
public string SupplyPointName { get; set; }
public int SupplyPointTypeId { get; set; }
public DateTime SupplyPointEffectiveDateTime { get; set; }
public string GazateerRef { get; set; }
public virtual SupplyPointType SupplyPointType { get; set; }
//[ForeignKey("SupplyPointId")]
public virtual SupplyPointAddress SupplyPointAddress { get; set; }
}
public partial class SupplyPointAddress
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointAddressId { get; set; }
public int SupplyPointId { get; set; }
public string D5001_FreeDescriptor { get; set; }
public string D5002_SubBuildingName { get; set; }
public string D5003_BuildingName { get; set; }
public string D5004_BuildingNumber { get; set; }
public string D5005_DependentThoroughfareName { get; set; }
public string D5006_DependentThoroughfareDescriptor { get; set; }
public string D5007_ThoroughfareName { get; set; }
public string D5008_ThoroughfareDescriptor { get; set; }
public string D5009_DoubleDependentLocality { get; set; }
public string D5010_DependentLocality { get; set; }
public string D5011_PostTown { get; set; }
public string D5012_County { get; set; }
public string D5013_Postcode { get; set; }
public virtual SupplyPoint SupplyPoint { get; set; }
}
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPoint> SupplyPoints { get; set; }
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPointAddress> SupplyPointAddresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SupplyPointAddress>()
.HasOptional<SupplyPoint>(u => u.SupplyPoint)
.WithRequired(c => c.SupplyPointAddress).Map(p => p.MapKey("SupplyPointId"));
base.OnModelCreating(modelBuilder);
}
I moved the foreign key into SupplyPoint table so that the foreign key was being defined as SupplyPointAddressId in SupplyPoint. This worked and allows me to do SupplyPoint.SupplyPointAddress in resultant model
Since you're testing with a real DB. Use some of the
Database Initialization Strategies in Code-First:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
(Excerpt from this site)
It is pretty self explanatory.
If there's already a DB created, it just DROPs it.
Happy coding!
Why Appharbor not create all tables.
I have the following Entity Framework Configuration.
public class RezaWebContext : DbContext
{
public RezaWebContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<RegistrantInfo> RegistrantInfos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<RegistrantInfo>().HasRequired(x => x.UserProfile).WithOptional(x => x.RegistrantInfo);
}
}
public class RegistrantInfo
{
public virtual int RegistrantInfoId { get; set; }
public virtual string Name { get; set; }
public virtual string Sex { get; set; }
public virtual string BirthPlace { get; set; }
public virtual string BirthDate { get; set; }
public virtual string Address { get; set; }
public virtual string ExamNumber { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
//this tables used by ASP.Net Simple Membership
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual RegistrantInfo RegistrantInfo { get; set; }
}
connString :
<add name="DefaultConnection" connectionString="server=localhost\SqlExpress; database=RezaWeb;
user id=sa; password=123456; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
in my computer. All database tables created.
RegistrationInfo + SimpleMembership tables (UserProfile, webpages_Membership, webpages_OAuthMembership, webpages_Roles, webpages_UsersInRoles)
in appharbor : all SimpleMembership tables created but "RegistrationInfo" table not created.
Why ?