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.
Related
I am trying to find a simple way using AutoMapper to return all companies that are linked to a specific User Id in a many-to-many relationship scenario. I followed the SO Automapper many to many mapping but I get the error message "Expression of type 'System.Collections.Generic.List`1[API.Entities.CompanySetting]' cannot be used for parameter of type 'System.Linq.IQueryable" when trying to follow the logic.
My AppUser entity:
public class AppUser
{
public int Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
My CompanySetting entity:
public class CompanySetting
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
And I have the Join table
public class AppUserCompanySetting
{
public int AppUserId { get; set; }
public virtual AppUser AppUser { get; set; }
public int CompanySettingsId { get; set; }
public virtual CompanySetting CompanySettings { get; set; }
}
I then created a CompanySettingDto
public class CompanySettingDto
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
}
And a MemberDto:
public class MemberDto
{
public int Id { get; set; }
public string Username { get; set; }
public string PhotoUrl { get; set; }
public string KnownAs { get; set; }
public int TimeActive { get; set; }
public DateTime LastActive {get; set;}
public ICollection<PhotoDto> Photos { get; set; }
public ICollection<CompanySettingDto> CompanyInformation { get; set; }
}
I then tried Automapper to bring the relationships between the User and the Company Information I require:
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<AppUser, MemberDto>()
.ForMember(dest => dest.CompanyInformation, opt => opt.MapFrom(x => x.AppUserCompanySettings.Select(y => y.CompanySettings).ToList()))
CreateMap<CompanySetting, CompanySettingDto>();
}
}
I am writing an API call to get all companies that are linked to a specific UserId.
public async Task<IEnumerable<MemberDto>> GetCompaniesByUserIdAsync(int userId)
{
return await _context.Users
.Where(x => x.Id == userId)
.ProjectTo<MemberDto>(_mapper.ConfigurationProvider)
.ToListAsync();
}
I want to sort by Module Code. I tried adding OrderBy(m => m.code) but the error says 'does not contain a definition for 'OrderBy'...'.
public async Task<IEnumerable<Module>> GetAllModules()
{
return await context.Modules
.Include(m => m.Lecturers)
.ThenInclude(ml => ml.Lecturer)
.ToListAsync();
}
Module class:
public class Module
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public ICollection<ModuleLecturer> Lecturers { get; set; }
public Module()
{
Lecturers = new Collection<ModuleLecturer>();
}
}
ModuleLecturer class:
public class ModuleLecturer
{
public int ModuleId { get; set; }
public int LecturerId { get; set; }
public Module Module { get; set; }
public Lecturer Lecturer { get; set; }
}
Lecturer class:
public class Lecturer
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
Why is there a UserProgramRefProgramCharacteristics.RefProgramCharacteristicsId field??? There should only be 2 fields not 3. Right? Below are the 3 classes and the OnModelCreating that is needed to create a many to many table
public class RefProgramCharacteristic
{
public int Id { get; set; }
public string ProgramCharacteristic { get; set; }
public List<UserProgramRefProgramCharacteristic> UserProgramRefProgramCharacteristics { get; set; }
// public ICollection<UserProgram> userPrograms { get; } = new List<UserProgram>();
// public virtual ICollection<UserProgram> UserPrograms { get; set; }
}
public class UserProgram
{
public int Id { get; set; }
//UserProgramSaved
public bool MyList { get; set; }
public float MyPriorityRating { get; set; }
public int Similarity { get; set; }
public bool Compare { get; set; }
//UserProgramSimilarity
public int OverallSimilarityScore { get; set; }
public int DeltaProfileElement1_WorkExp { get; set; }
public int DeltaProfileElement2_VolExp { get; set; }
public int DeltaProfileElement3_ResExp { get; set; }
public int DeltaProfileElement4_Pubs { get; set; }
public int DeltaProfileElement5_Step1 { get; set; }
public int DeltaProfileElement6_Step2ck { get; set; }
public int DeltaProfileElement7_Aoa { get; set; }
public int DeltaProfileElement8_Nspecialties { get; set; }
public int DeltaProfileElement9_PercentApps { get; set; }
//UserComparisonSaved
// public RefProgramCharacteristic RefProgramCharacteristic { get; set; }
public string RefProgramCharacteristicList { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int MedicalProgramId { get; set; }
public RefProgramDetailData MedicalProgram { get; set; }
public List<UserProgramRefProgramCharacteristic> UserProgramRefProgramCharacteristics { get; set; }
// public ICollection<RefProgramCharacteristic> RefProgramCharacteristics { get; } = new List<RefProgramCharacteristic>();
// public virtual ICollection<RefProgramCharacteristic> RefProgramCharacteristics { get; set; }
}
public class UserProgramRefProgramCharacteristic
{
// public int Id { get; set; }
public int UserProgramId { get; set; }
public UserProgram UserProgram { get; set; }
public int RefProgramCharacteristicsId { get; set; }
public RefProgramCharacteristic RefProgramCharacteristic { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<UserProgramRefProgramCharacteristic>()
.HasKey(t => new { t.UserProgramId, t.RefProgramCharacteristicsId });
base.OnModelCreating(builder);
}
Why is there a UserProgramRefProgramCharacteristics.RefProgramCharacteristicsId field?
Because you are telling EF Core to create such field here:
public int RefProgramCharacteristicsId { get; set; }
// ^
While the navigation property is called RefProgramCharacteristic (no s). And by EF Core conventions:
If the dependent entity contains a property named <primary key property name>, <navigation property name><primary key property name>, or <principal entity name><primary key property name> then it will be configured as the foreign key.
RefProgramCharacteristicsId does not match any of these rules, so EF Core creates a shadow FK property with default name RefProgramCharacteristicId.
Either rename the property to RefProgramCharacteristicId (best), or map it explicitly using ForeignKey data annotation:
[ForeignKey(nameof(RefProgramCharacteristicsId))]
public RefProgramCharacteristic RefProgramCharacteristic { get; set; }
or
[ForeignKey(nameof(RefProgramCharacteristic))]
public int RefProgramCharacteristicsId { get; set; }
or using HasForeignKey fluent API:
builder.Entity<UserProgramRefProgramCharacteristic>()
.HasOne(e => e.RefProgramCharacteristic)
.WithMany(e => e.UserProgramRefProgramCharacteristics)
.HasForeignKey(e => e.RefProgramCharacteristicsId);
I'm using the ASP Net Core 2.
I have a test model:
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public int Age { get; set; }
[IgnoreDataMember]
public ICollection<PlayerTeam> PlayerTeams { get; set; }
public Player()
{
PlayerTeams = new List<PlayerTeam>();
}
}
public class PlayerTeam
{
public int PlayerId { get; set; }
public Player Player { get; set; }
public int TeamId { get; set; }
public Team Team { get; set; }
}
public class Team
{
public int Id { get; set; }
public string Name { get; set; } // название команды
// [IgnoreDataMember]
public ICollection<PlayerTeam> PlayerTeams { get; set; }
public Team()
{
PlayerTeams = new List<PlayerTeam>();
}
}
this is my DBcontext:
public class FootbollContext: DbContext
{
public DbSet<Player> Players { get; set; }
public DbSet<Team> Teams { get; set; }
public FootbollContext(DbContextOptions<FootbollContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PlayerTeam>()
.HasKey(t => new { t.TeamId, t.PlayerId });
}
}
I have a query in my controller:
FootbollContext db;
var teams = db.Teams.Select(team => new {
TeamName = team.Name,
PlayersOlder20 = team.PlayerTeams.Where(pt => pt.Player.Age > 20).Select(s => s.Player)
});
and it works fine, but I want to use the Include()/ThenInclude() methods for this query, and I want to get the same equal results ie.
var teams = db.Teams.Include(p => p.PlayerTeams).ThenInclude(d => d.Player)
but I don't want to load all data! and I don't know how I can filter results by property "Players age (> 20)" in the relative table (not in the selectable!!) in one SQL Query.
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>