How to acess a table in Code-First-Database? - c#

For my Project I want to access the database but I have no clue because it is my first time programming with ASP.net mvc.
I have already read through a bunch of guides but to no avail.
Controller
This right here is my controller which gets a Code from a Machine (e.g.: 123456) but when I want to access the database through this option I get the No database provider has been configured for this DbContext. Error Message.
namespace Qualitätskontrolle.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult StartPage(string Code)
{
Debug.WriteLine(Code);
ApplicationDbContext dbContext = new ApplicationDbContext(.);
var dbErgebnisse = dbContext.Result.ToList();
for (int i = 0; i < dbErgebnisse.Count; i++)
{
Debug.WriteLine(dbErgebnisse[i]);
}
return View();
}
}
Context Class
I have read that the empty constructor should be removed but then I cannot access it in the Controller class.
namespace Qualitätskontrolle.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Bilder> Bilder { get; set; }
public DbSet<Prüfungen> Prüfungen { get; set; }
public DbSet<Ergebnis> Result { get; set; }
public DbSet<Typen> Typen { get; set; }
public DbSet<Typen_Pruefungen_Bilder> Typen_Pruefungen_Bilder { get; set; }
public DbSet<Einstellungen_KoordinatenSys> Einstellungen_KoordinatenSys { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Einstellungen_KoordinatenSys>()
.HasKey(c => new { c.ID, c.BildID });
modelBuilder.Entity<Ergebnis>()
.HasKey(c => new { c.BildID, c.TypenID, c.PruefungenID, c.BauTeilId });
modelBuilder.Entity<Typen_Pruefungen_Bilder>()
.HasKey(c => new { c.PruefungenID, c.TypenID });
}
}
}
Model
This is the model I need. I speficly need the BauTeilId for the Controller Class.
namespace Qualitätskontrolle.Models
{
public class Ergebnis
{
[Key]
public int TypenID { get; set; }
[Key]
public int PruefungenID { get; set; }
[Key]
public int BildID { get; set; }
[Key]
[StringLength(254)]
public string BauTeilId { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
public string XLabel { get; set; }
public int? X { get; set; }
public string YLabel { get; set; }
public int? Y { get; set; }
public string FehlerCode { get; set; }
public string FehlerName { get; set; }
public string FehlerGruppe1 { get; set; }
public string FehlerGruppe2 { get; set; }
public int Result { get; set; }
//1=IO 2=NIO
}
The result should be a list of BauTeilId which I can then check with the Code from the Controller.
If you need further information I will reply quickly.

I'm assume that it's not asp.net mvc core.
You should create separate class which implement DbContext e.g
public class ApplicationCustomDbContext : DbContext
{
public ApplicationCustomDbContext () : base("name=DefaultConnectionCustom")
{
}
// DbSet for your Entities
}
and in web.config you should specific connection string e.g.
<connectionStrings>
<add name="DefaultConnectionCustom" providerName="System.Data.SqlClient" connectionString="___" />
</connectionStrings>

There are multiple issues.
For ApplicationDbContext in .net core, you should register like below in Startup.cs
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
context.Configuration.GetConnectionString("ApplicationDbContextConnection")));
For connectionstring, you could configure in appsettings.json like
{
"ConnectionStrings": {
"ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CoreMVC2_2;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
For use, you could resolve from constructure like
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_mapper = mapper;
_context = context;
_userManager = userManager;
_userStore = userStore;
}
public async Task<IActionResult> Index()
{
var existingStudent = _context.Result.ToList();
return View();
}
}

Related

Entity Framework Core : insert error (Serialization and deserialization of 'System.Action' instances are not supported. Path: $.MoveNextAction.)

I am trying to preform a insert action using Entity Framework Core 6.0.11 with identity framework as the base, with Postgres as the database.
I am getting the following error when trying to preform an insert operation:
Serialization and deserialization of 'System.Action' instances are not supported. Path: $.MoveNextAction
This is the code of my insert:
public async Task<CampaignDetialDto> CreateCampaign(BaseCampaignDto campaignDto)
{
var userCampaign = new UserCampaign
{
UserId = UserId,
Campaign = _mapper.Map<Campaign>(campaignDto),
CampaignRole = CampaignRoleEnum.Player
};
await _userCampaignRepo.AddAsync(userCampaign);
return _mapper.Map<CampaignDetialDto>(userCampaign.Campaign);
}
The userCampaignRepo:
public class UserCampaignRepository : GenericRepository<UserCampaign>, IUserCampaignRepository
{
private readonly PostGresContext _context;
private readonly IMapper _mapper;
public UserCampaignRepository(PostGresContext context, IMapper mapper) : base(context, mapper)
{
_context = context;
_mapper = mapper;
}
}
The base repo preforming the action:
public async Task<T> AddAsync(T entity)
{
await _context.AddAsync(entity);
await _context.SaveChangesAsync();
return entity;
}
The context and models:
public class PostGresContext : IdentityDbContext<User>
{
public PostGresContext(DbContextOptions options) : base(options)
{
}
public DbSet<Campaign> Campaigns { get; set; }
public DbSet<UserCampaign> UserCampaigns { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new RoleConfiguration());
modelBuilder.Entity<UserCampaign>().HasKey(x => new
{
x.UserId,
x.CampaignId
});
}
}
public class UserCampaign
{
[Key, Column(Order = 0)]
public string UserId { get; set; }
public virtual User User { get; set; }
[Key, Column(Order = 1)]
public int CampaignId { get; set; }
public virtual Campaign Campaign { get; set; }
public CampaignRoleEnum CampaignRole { get; set; } = CampaignRoleEnum.Player;
}
public class Campaign
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
public ActiveStateEnum Active { get; set; } = ActiveStateEnum.Active;
public virtual ICollection<UserCampaign> UserCampaigns { get; set; }
}
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<UserCampaign> UserCampaigns { get; set; }
}
public static IServiceCollection AddApplicationPostGresContext(this IServiceCollection services, IConfiguration _config)
{
services.AddDbContext<PostGresContext>(options =>
{
options.UseNpgsql(_config.GetConnectionString("PostGresConnectionString"));
});
return services;
}
I tried altering the add methods hoping it might bring a change but with no effect, I also tried to call the context directly by using _context.addAsync(XXX) or _context.SaveChangesAsync() - this also had the same results.
I would like to add a model into the Postgres database.

Generic class of one type to another type in auto mapper

I have this Generic Pagination class: i want to map PagedList<Caste> to PagedList<CasteModel>
public class PagedList<T>
{
public PagedList()
{
}
public PagedList(IList<T> source, int pageNumber, int pageSize)
{
this.TotalItems = source.Count;
this.PageNumber = pageNumber;
this.PageSize = pageSize;
this.Items = source;
}
public int TotalItems { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public IEnumerable<T> Items { get; set; }
public int TotalPages => (int)Math.Ceiling(this.TotalItems / (double)this.PageSize);
}
And Model and View Model Classes
public class Caste
{
public int Id { get; set; }
public string CasteCode { get; set; }
public string CasteDesc { get; set; }
public bool IsActive { get; set; }
public int? CasteParentId { get; set; }
public virtual Caste CasteParent { get; set; }
public virtual ICollection<Caste> CasteChildren { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class CasteModel
{
public int Id { get; set; }
public string CasteCode { get; set; }
public string CasteDesc { get; set; }
public bool IsActive { get; set; }
public int? CasteParentId { get; set; }
}
and below is my auto mapper configuration
public class AppProfile : Profile
{
public AppProfile()
{
//Masters
CreateMap<CasteModel, Caste>();
CreateMap<Caste, CasteModel>();
CreateMap(typeof(PagedList<>), typeof(PagedList<>));
// CreateMap<PagedList<Caste>, PagedList<CasteModel>>(); ---This also checked
}
This is the code for mapping in controller
PagedList<Caste> result = new PagedList<Caste>
{
Items = new List<Caste> { new Caste { Id = 7, CasteCode="" } },
TotalItems = 1
};
var pagedListOfDtos = Mapper.Map<PagedList<CasteModel>>(result);
When executing below error am getting below exception
"Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance."
Am using Asp.net core and automapper 6.1. Code is written based on below link
generic list to automapper
Please suggest a me solution tried a lot all getting same message
For Mapper.Map<PagedList<CasteModel>>(result);, you need to initialize Mapper like below in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile<AppProfile>();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
But, it it recommended to use Dependence Injection to resolve Mapper.
Install Package AutoMapper.Extensions.Microsoft.DependencyInjection
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
UseCase
public class ValuesController : ControllerBase
{
private readonly IMapper _mapper;
public ValuesController(IMapper mapper)
{
_mapper = mapper;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
PagedList<Caste> result = new PagedList<Caste>
{
Items = new List<Caste> { new Caste { Id = 7, CasteCode = "" } },
TotalItems = 1
};
var pagedListOfDtos = _mapper.Map<PagedList<CasteModel>>(result);
return new string[] { "value1", "value2" };
}
}

How to use Automapper with ASP.NET Core 2.2 API

This is the error I get:
System.InvalidOperationException: Unable to resolve service for type
'myBackEnd.Entities.Striper' while attempting to activate
'myBackEnd.Controllers.StripeController'.
at
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
I am working on using Automapper for the first time. I am also new to NET. I am using an HTTPPOST to get data from the front end in the format
amount : string;
currency : string;
description : string;
token : string;
name: string;
address_city: string;
address_line1: string;
address_line2: string;
address_state: string;
address_zip: string;
address_country: string;
I have stripe.cs and stripeDto.cs files:
public class Striper
{
public object Amount { get; set; }
public string Currency { get; set; }
public object Description { get; set; }
public string Token { get; set; }
public string Name { get; set; }
public string Address_line1 { get; set; }
public string Address_line2 { get; set; }
public string Address_state { get; set; }
public string Address_zip { get; set; }
public string Address_country { get; set; }
}
stripeDto:
public class StripeDto
{
public object Amount { get; set; }
public string Currency { get; set; }
public object Description { get; set; }
public string Token { get; set; }
public string Name { get; set; }
public string Address_line1 { get; set; }
public string Address_line2 { get; set; }
public string Address_state { get; set; }
public string Address_zip { get; set; }
public string Address_country { get; set; }
}
This is the mapping profile file:
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Striper, StripeDto>();
CreateMap<StripeDto, Striper>();
}
}
Finally this is the Controller:
private readonly AppDbContext _context;
private IMapper _mapper;
public StripeController(AppDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<IActionResult> PostCreditCardData([FromBody] StripeDto stripeDto)
{
Console.WriteLine("got this from the front end", stripeDto);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.StripeDto.Add(stripeDto);
// Instantiate source object stripe
await _context.SaveChangesAsync();
_striper = _mapper.Map<Striper>(stripeDto);
return Ok(_striper);
}
I get this error in visual studio "Unable to resolve service for type 'myBackEnd.Entities.Striper'"
Here is the startup.cs code:
services.AddAutoMapper();
Your AutoMapper configuration in Startup class should be as follows:
public void ConfigureServices(IServiceCollection services)
{
// Auto Mapper Configurations
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
//........
}
First, you must install Automapper dependency injection package:
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
Call services.AddAutoMapper() in ConfigureServices method in the Startup class.
More on this at:
https://dotnetcoretutorials.com/2017/09/23/using-automapper-asp-net-core/
I know it's too late
but it's because of your startup and AutoMapper configuration
services.AddAutoMapper(typeof(MappingProfile).Assembly);
best regards

How do I get all child collection with generic repository pattern?

I'm using EF Core 2.1 and I have these class in my Domain.
public class HomeSection2
{
public HomeSection2()
{
HomeSection2Detail = new List<HomeSection2Detail>();
}
public Guid ID { get; set; }
public string Title { get; set; }
public string Header { get; set; }
public List<HomeSection2Detail> HomeSection2Detail { get; set; }
}
public class HomeSection2Detail
{
public Guid ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public int? Sequence { get; set; }
public HomeSection2 HomeSection2 { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
//HomeSection2
modelBuilder.Entity<HomeSection2>().HasKey(s => s.ID);
modelBuilder.Entity<HomeSection2>().Property(s => s.ID).ValueGeneratedOnAdd();
modelBuilder.Entity<HomeSection2>().Property(s => s.Title).IsRequired();
modelBuilder.Entity<HomeSection2>().Property(s => s.Header).IsRequired();
//HomeSection2Detail
modelBuilder.Entity<HomeSection2Detail>()
.HasOne(p => p.HomeSection2)
.WithMany(b => b.HomeSection2Detail);
modelBuilder.Entity<HomeSection2Detail>().HasKey(s => s.ID);
modelBuilder.Entity<HomeSection2Detail>().Property(s => s.ID).ValueGeneratedOnAdd();
modelBuilder.Entity<HomeSection2Detail>().Property(s => s.Title).IsRequired();
modelBuilder.Entity<HomeSection2Detail>().Property(s => s.Sequence).IsRequired();
}
And I have a generic repo
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList();
}
}
When I call GetAll from the Application var obj = _uow.HomeSection2s.GetAll() like this, it won't fill the Detail.
What you mean is reffered to as 'Lazy Loading'. It would require you to make those properties virtual, like:
public virtual List<HomeSection2Detail> HomeSection2Detail { get; set; }
You can also take a look at this anwser
More documentation on loading related data

Using Multiple Databases within a controller asp.net mvc

I have two separate VS Solutions both work fine accessing the databases associated with them.
How ever I need to look up some details from the other database to be displayed in the other solution.
Ive added the second connection string to the web.config and then added the context to my DAL:
namespace RACentral.DAL
{
public class RACentralContext : DbContext
{
public RACentralContext()
: base("RACDev")
{
}
public DbSet<RiskAssessment> RiskAssessments { get; set; }
public DbSet<Hazard> Hazards { get; set; }
public DbSet<PPE> PPEs { get; set; }
public DbSet<RiskAssessmentPPE> RiskAssessmentPPEs { get; set; }
public DbSet<PeopleExposed> PeopleExposeds { get; set; }
public DbSet<RiskAssessmentPeopleExposed> RiskAssessmentPeopleExposeds { get; set; }
public DbSet<RiskAssessmentHazard> RiskAssessmentHazards { get; set; }
public DbSet<ControlMeasure> ControlMeasures { get; set; }
public DbSet<Severity> Severitys { get; set; }
public DbSet<Likelihood> Likelihoods { get; set; }
public DbSet<AddControlMeasure> AddControlMeasures { get; set; }
public DbSet<Type> Types { get; set; }
public DbSet<SubType> SubTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class PeopleContext : DbContext
{
public PeopleContext()
: base("PeopleContext")
{
}
public DbSet<Person> People { get; set; }
}
}
I get an error in the controller
'Not set to an instance of an object,'
Am trying to access it in my controller as follow:
public class RiskAssessmentController : Controller
{
private RACentralContext db = new RACentralContext();
private PeopleContext Peopledb = new PeopleContext();
public ViewResult StartRA()
{
var user = User.Identity.Name;
string userName = user.Substring(7);
var test = Peopled.Person.FirstOrDefault(x => x.PersonId == 1) //Error here
StartRiskAssessmentViewModel viewModel = new StartRiskAssessmentViewModel
{
RiskAssessment = new RiskAssessment(),
Assessor = userName,
};
return View(viewModel);
}
}

Categories

Resources