How can I access the AspNetUsers table's columns? - asp.net-core

So, I have this custom user that has properties FullName and ProfileImage.
I have made everything properly and in the dbo.AspNetUsers table in the database I see that the two columns are there and are populated.
However, when I try to access those columns in the database there is nothing suggested via IntelliSense and I can't access them for the life of me.
Been reading around about it, however I could not figure out why I can't access it.
Pseudocode example
private readonly OnlineCardShopDbContext data;
...
public SomeConstructor(OnlineCardShopDbContext data){
this.data = data;
}
...
var dbUsers = this.data.Users.{none of the two columns' names here}

You can't access the columns with this query.
You should use LINQ methods like Where or Select ie with this query you can select only FullName:
var dbUsers = this.data.Users.Select(user=>new { user.FullName }).ToList();
Read more in link

Related

RepoDb cannot find mapping configuration

I'm trying to use RepoDb to query the contents of a table (in an existing Sql Server database), but all my attempts result in an InvalidOperationException (There are no 'contructor parameter' and/or 'property member' bindings found between the resultset of the data reader and the type 'MyType').
The query I'm using looks like the following:
public Task<ICollection<MyType>> GetAllAsync()
{
var result = new List<MyType>();
using (var db = new SqlConnection(connectionString).EnsureOpen())
{
result = (await db.ExecuteQueryAsync<MyType>("select * from mytype")).ToList();
}
return result;
}
I'm trying to run this via a unit test, similar to the following:
[Test]
public async Task MyTypeFetcher_returns_all()
{
SqlServerBootstrap.Initialize();
var sut = new MyTypeFetcher("connection string");
var actual = await sut.GetAllAsync();
Assert.IsNotNull(actual);
}
The Entity I'm trying to map to matches the database table (i.e. class name and table name are the same, property names and table column names also match).
I've also tried:
putting annotations on the class I am trying to map to (both at the class level and the property level)
using the ClassMapper to map the class to the db table
using the FluentMapper to map the entire class (i.e. entity-table, all columns, identity, primary)
putting all mappings into a static class which holds all mapping and configuration and calling that in the test
providing mapping information directly in the test via both ClassMapper and FluentMapper
From the error message it seems like RepoDb cannot find the mappings I'm providing. Unfortunately I have no idea how to go about fixing this. I've been through the documentation and the sample tutorials, but I haven't been able to find anything of use. Most of them don't seem to need any mapping configuration (similar to what you would expect when using Dapper). What am I missing, and how can I fix this?

ASP.NET MVC 4 Deferred query execution not retrieving data from database

I am new in ASP.NET MVC 4. In my project I am using Code First technique in of EF. I want to retrieve some data from database and I used following code for this :
List<SelectListItem> ls = new List<SelectListItem>();
var lm = from m in db.BOs //fetch data from database
select m;
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
}
But when execution pointer move inside foreach it immediately come back out of the loop showing return ls value Count = 0. Code does not giving me any error while running that's why I am not getting where is going wrong.
UPDATE: I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. So How I overcome this??
decorate your BO class with Table("BO") to specify the table name (attribute is in System.ComponentModel.DataAnnotations.Schema namespace)
[Table("BO")]
public partial class BO
{
...
Write following code inside DbContext class :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
The modelBuilder.Conventions.Remove statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.

DBIx Class: overloading new() in a resultset

Hello dear community members.
I have a following problem. Say, I have a user table. During my programming I create a lot of search queries to this table. Then, later, I realize that I need to select always only "active" users, i.e. with "active" column set to TRUE. Now, instead of adjusting all my queries to the user table with additional filter (active => "true"), is it possible to overload new() in the resultset class or to do something that will globally change all my queries in the way I need?
Thanks a lot in advance.
Add a method to your User ResultSet class that returns a filtered resultset, for example:
sub search_active {
my $self = shift;
return $self->search({ active => 1 });
}
Also see the DBIx::Class docs on 'predefined searches' for more information.

Get table names from Fluent Nhibernate

After you have setup your mappings in fluent nhibernate, is there a way of getting the table name for an entity from the class type?
I have read in regular nhiberante you can do something like cfg.GetClassMapping(typeof (Employee)). I would like to do the type of thing to retrieve the database table name.
Is this possible as standard or how would I go about this?
The fluent nhibernate way:
var userMetadata = sessionFactory.GetClassMetadata(typeof(SomeEntity)) as NHibernate.Persister.Entity.AbstractEntityPersister;
var cols = userMetadata.KeyColumnNames;
var table = userMetadata.TableName;
where sessionFactory is of type ISessionFactory.
Assuming you have done this at some point:
FluentNHibernate.Cfg.FluentConfiguration fluentConfig = FluentNHibernate.Cfg.Fluently.Configure();
Then all you have to do is this:
string tableName = fluentConfig.BuildConfiguration().GetClassMapping(typeof (One of your data entities)).Table.Name;
Worked great in my implementation of a generic "GetAllItems" routine.
Hi I'm using this to create Full Text Catalogs on M$ Sql Server, using almost same mechanism of FluentNhibernate mapping.
From Configuration I get a list of persistentClasses
this.persistenClasses = configuration.ClassMappings;
Next I search through this list to find my persistenClass class by its Generic type of mapping class
var genericDefinition = mappingClass.BaseType.GetGenericArguments()[0];
var matchedPersistClass = FindPersistedClassFrom(genericDefinition);
private PersistentClass FindPersistedClassFrom(Type genericDefinition)
{
return persistentClasses.FirstOrDefault(x => x.EntityName == genericDefinition.FullName);
}
So having persistentClass you easily have access to Table Name, properties, db fields, etc.
TableName = matchedPersistClass.Table.Name,
cfg.GetClassMapping(typeof(Employee)).Table.Name will also work, and seems to be much simpler.

How do I stop AutoMapper from making two identical SELECT statements with NHibernate?

I have an entity called Incident and a DTO called IncidentDTO. For now, IncidentDTO simply looks like this:
public class IncidentDTO : Incident
{
// empty until I can get AutoMapper working correctly
}
I'm trying to pull a list of all the Incidents in the database and convert them to DTOs using this code:
Mapper.CreateMap<Incident, IncidentDTO>();
using (var session = SessionFactory.OpenSession())
{
var incidents = session.Linq<Incident>();
var incidentDTOs = Mapper.Map(incidents, new List<IncidentDTO>());
}
This code works fine, except when I use NHProf to look at the SQL statements being generated, I get this:
SELECT ... FROM [Incident] this_
SELECT ... FROM [Incident] this_
The two SELECT statements are exactly identical. Why does AutoMapper generate two identical SELECT statements, and how do I prevent it from doing this?
A guess: Enumerating IQueryable creates a separate select for every item. Solve it with enumerating IList.
var incidents = session.Linq<Incident>().ToList();
I would probably do this to prevent another problem.
int someReasonableNumber = 1000;
var incidents = session.Linq<Incident>().Take(someReasonableNumber).ToList();
This is just a guess, not something I really know.
I think your problem is related with this issue: