Accessing to a table by the string name LINQ - c#

I would like to access to a database table from an string identifier belonging to an equipement. I need to do it like this way because according to the equipement selected I will have an string with the table name with data to request. I test the access to my database and everything is ok.
How to resolve this issue please? Thanks in advance
Request:
var query = (from donnees in "String Name of my table"
where donnees.Chrono >= dateDebut.Ticks
select donnees).Any();
My database class:
public partial class PcVueContext : DbContext
{
public PcVueContext()
{
}
public PcVueContext(DbContextOptions<PcVueContext> options)
: base(options)
{
}
public virtual DbSet<AICommonParameters> AICommonParameters { get; set; }
public virtual DbSet<tab_LOG_TRACA> tab_LOG_TRACA { get; set; }
public virtual DbSet<tab_UA_ACT> tab_UA_ACT { get; set; }
public virtual DbSet<tab_UA_CUV> tab_UA_CUV { get; set; }
public virtual DbSet<tab_UA_ECR> tab_UA_ECR { get; set; }
public virtual DbSet<tab_UA_ENG> tab_UA_ENG { get; set; }
public virtual DbSet<tab_UA_EVAA> tab_UA_EVAA { get; set; }

Related

Is it possible to add array of data in child entity?

I have issue that I hope someone here will be able to help me.For this exercise I`m using aspnetboilerplate framework.
So I create 3 entity and they ALL work good (at least I guess they work good)
Little bit recap of project
One Recepie HAVE one or more Ingredient
Ingrident.cs
public class Ingrident : Entity
{
public string Name { get; set; }
public Master Master { get; set; }
public int? MasterId { get; set; }
public Recepie Recepie { get; set; }
public int? RecepieId { get; set; }
}
Master.cs
public class Master : Entity
{
public string Name { get; set; }
public string? Image { get; set; }
public string? ShortDescription { get; set; }
public string? FullDescription { get; set; }
public string? Keywords { get; set; }
public string Slug { get; set; }
public int? Count { get; set; }
public List<Ingrident> Ingridents { get; set; }
}
Recepie.cs
public class Recepie : Entity
{
public string RecepieName { get; set; }
public Ingrident Ingridents { get; set; }
}
With this database structure I can add Recepie and add only one ingredient when I try to send [] of Ingredient its show me DTO error.
And here is RecepieAppService.cs
public class RecepieAppService : AsyncCrudAppService<IndexIngrident.Entities.Recepie,RecepieDto>
{
private readonly IRepository<IndexIngrident.Entities.Recepie> _repository;
private readonly IRepository<IndexIngrident.Entities.Ingrident> _ingRepository;
public RecepieAppService(IRepository<IndexIngrident.Entities.Recepie> repository, IRepository<IndexIngrident.Entities.Ingrident> ingRepository)
: base(repository)
{
_repository = repository;
_ingRepository = ingRepository;
}
public List<RecepieFullGetDto> GetAllIncluded()
{
var result = _repository.GetAllIncluding(x => x.Ingridents , x => x.Ingridents.Master);
Debug.WriteLine(result);
return ObjectMapper.Map<List<RecepieFullGetDto>>(result);
}
}
RecepieDto.cs
[AutoMap(typeof(IndexIngrident.Entities.Recepie))]
public class RecepieDto : EntityDto
{
public string RecepieName { get; set; }
public IngridentRecepieDto Ingridents { get; set; }
}
public class IngridentRecepieDto : EntityDto
{
public string Name { get; set; }
public int RecepieId { get; set; }
}
Using AsyncCrudAppService my CRUD is automatically generated and I`m able to create new Recepie but when I try to do something like this
I get error
you need to add the mapping of objects in both directions, [AutoMapTo (typeof (RecepieDto))] and [AutoMapFrom (typeof (Recepie))], and verify that you have the class, inherits AutomapperProfile

"Column names in each table must be unique." during database update

I am quite new to ASP.NET at all, however this is my first app with ASP.NET Core. I have problem with updating database after creating the migration. While I type command: dotnet ef database update, I get error:
Column names in each table must be unique. Column name 'PortalUserId'
in table 'Adverts' is specified more than once.
I think the problem is with my model structure, but I do not know what I am doing wrong. When I was developing with ASP.NET MVC 5 everything was Ok.
Here is my Model (without unnecessary for the case entities):
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<PortalUser> PortalUsers { get; set; }
public DbSet<Advert> Adverts { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
public class Advert
{
public int ID { get; set; }
public string Title { get; set; }
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
public int PortalUserID { get; set; }
public PortalUser PortalUser { get; set; }
}
public class PortalUser : IdentityUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public ICollection<Advert> Adverts { get; set; }
}
What I am doing here is normal virtual mapping for lazy loading purposes. I am storing FK to PortalUser in Advert field.
I will appreciate every helpful answer!
I already figure out, that lazy loading is not supported so now my model looks like in the official tutorial:
https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
Okay, guys, I found the solution! All what is needed, it is change type of property PortalUserId from int to string. Than everythings compiles and no doubled field appears!
Thanks for at least trying to help me!

How to check if data exist in SQL table using EF code first in ASP.NET MVC application?

I have this model class:
public class MembershipSerial
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue=false)]
public string Serial { get; set; }
[Required]
[Display(Name="Membership Serial")]
public string SerialConfirmed { get; set; }
}
I am using EF code-first approach, I would like to check the value of the Serial vs SerialConfirmed and find any Serial which is equal to SerialConfirmed.
I tried below but i get a null exception and don't know how to solve this?
public ActionResult Checkout(UserDetails Details)
{
if (Details.MembershipSerial.Serial.Any().ToString() == Details.MembershipSerial.SerialConfirmed)
{
return View("UserSerial");
}
return View();
}
public class UserDetails : IdentityUser
{
public virtual DeliveryDetails DeliveryDetails { get; set; }
public virtual UserOrders UserOrders { get; set; }
public virtual MembershipSerial MembershipSerial { get; set; }
}
Edit:
public class MembershipSerial
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue=false)]
public string Serial { get; set; }
[Required]
[Display(Name="Membership Serial")]
public string SerialConfirmed { get; set; }
}
public class DeliveryDetails
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string AddressLine2 { get; set; }
public string District { get; set; }
public string Province { get; set; }
}
public class UserOrders
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class MyDbContext : IdentityDbContext<UserDetails>
{
public MyDbContext()
: base ("EFDbContext")
{
}
public System.Data.Entity.DbSet<MembershipSerial> MembershipSerial { get; set; }
public System.Data.Entity.DbSet<DeliveryDetails> DeliveryDetails { get; set; }
public System.Data.Entity.DbSet<UserOrders> UserOrders { get; set; }
}
Any help is appreciated. Thanks in advance.
Your if statement should be like this:
if (Details.MembershipSerial.Serial == Details.MembershipSerial.SerialConfirmed)
Serial and Serial Confirmed are strings so you can just compare them
If you're trying to compare any Serial in the database with the SerialConfirmed that the user is Checking Out then you need a variable to hold a new instance of your connection string: assuming that MemberShipSerial is a table in your database...
using(var db = new ConnectionString())
{
if(db.MembershipSerial.Any(x => x.Serial.ToUpper() == Details.MembershipSerial.SerialConfirmed.ToUpper())
{
/*do something*/
}
}
if you just want to compare Serial and SerialConfirmed based on what the user typed in then use
if(Details.MembershipSerial.Serial.ToUpper() == Details.MembershipSerial.SerialConfirmed.ToUpper())
if the second option returns a null exception then you have to debug on the CheckingIn Action and see if what those properties are holding the values you are expecting

Code-First SQL Server ASP.NET MVC6

I am a VB.NET programmer, but I am trying to learn C# and MVC in my spare time. I am using ASP.NET MVC 5.1.0.0 and I am trying to do code-First database creation in a local instance of SQL Server.
I was able to get the first database table to update in the database when I ran Update-Database from within the IDE, but when I added a second table that has a PK/FK relationship with the first, I am getting a red line under [ForeignKey] which reads
Does not contain a constructor that takes 1 arguments
I have been searching all over and not getting anywhere. Any suggestions or help would be appreciated. By the way, the first table is a PK/FK relationship to the AspNetUsers table.
public class BuildDatabase : IdentityUser
{
public virtual Companies Companies { get; set; }
public virtual NotaryProfile NotaryProfile { get; set; }
}
public class Companies
{
[Key]
[Column("CompanyID")] // Did this as the database will reflect TableName_ColumnName instead.
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public bool IsActive { get; set; }
public bool IsNotary { get; set; }
public virtual ICollection<NotaryProfile> NotaryProfile { get; set; }
}
public class NotaryProfile
{
[Key]
public int NotaryID { get; set; }
public string NamePrefix { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public string NameSuffix { get; set; }
public bool IsActive { get; set; }
public int DefaultState { get; set; }
public int DefaultCounty { get; set; }
public bool IsSigningAgent { get; set; }
public bool HasABond { get; set; }
public decimal BondAmount { get; set; }
public bool HasEandO { get; set; }
public decimal EandOAmount { get; set; }
public bool ElectronicNotarizationsAllowed { get; set; }
public string ElectronicTechnologyUsed { get; set; }
public string ComissionNumber { get; set; }
public DateTime CommissionIssued { get; set; }
public DateTime CommssionOriginal { get; set; }
public DateTime CommissionExpires { get; set; }
public DateTime CommissionFiledOn { get; set; }
public string SOSAuditNumber { get; set; }
public string CommissionDesc { get; set; }
[Foreignkey("CompanyID")] // Companies.CompanyID = PK
public int CompanyID { get; set; } // PK/FK relationship.
public Companies Companies { get; set; } // Reference to Companies table above.
}
public class SchemaDBContext : IdentityDbContext<BuildDatabase>
{
public SchemaDBContext()
: base("DefaultConnection"){}
public DbSet<Companies> Companies { get; set; }
public DbSet<NotaryProfile> NotaryProfile { get; set; }
}
One of your classes (probably NotaryProfile) needs to reference another object (the foreign key relationship) but there is no constructor in that class that accepts an argument to establish that relationship, e.g.:
public NotaryProfile(int companyId) {
this.companyId = companyId;
}
BTW, a better way to establish that relationship is to use the actual class type rather than the ID, as in:
public class NotaryProfile {
...
public Company Company { get; set; }
// Instead of this:
// public int CompanyID { get; set; } // PK/FK relationship.
...
}
See also:
C# “does not contain a constructor that takes '1' arguments”
Does not contain a constructor that takes 2 arguments

How do I add another table to my database using Code First on MVC3 and Entity Framework?

I have an MVC3 project I created using the Code First paradigm and it works great. I created a model inheriting from DBContext, added the connection string, and I can write to the table and all that.
I can't seem to figure out how to add another table to the database using Code First, though. Adding another connection string that points to the same database doesn't work. Simply adding another class, creating a DBContext for it, and then adding and saving something to the new context doesn't work.
How do I add a new table to the database automatically using just code? My current web.config looks like this:
<add name="PersonDBContext"
connectionString="Data Source=|DataDirectory|PersonData.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
My working model looks like this:
public class Person
{
public int ID { get; set; }
public string name { get; set; }
public string country { get; set; }
public string gender { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> People { get; set; }
}
And finally what I want to create:
public class Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class DogDBContext : DbContext
{
public DbSet<Dog> Dogs { get; set; }
}
Why wouldn't you create single context for both classes?
public class Person
{
public int ID { get; set; }
public string name { get; set; }
public string country { get; set; }
public string gender { get; set; }
}
public class Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class ApplicationNameDBContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Dog> Dogs { get; set; }
}
Just use:
public class Person
{
public int ID { get; set; }
public string name { get; set; }
public string country { get; set; }
public string gender { get; set; }
}
public class Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Dog> Dogs { get; set; }
}

Categories