Reputation: 125
Using .NET Core 2.2.300 and Entity Framework Core 2.2.4.
I got two tables with similar contents on a SQL Server database, so I wrote a query like:
SELECT
A.guid_id AS Id
, A.document AS Document
FROM TableA A
WHERE
A.guid_user_id = 'valid guid in here'
UNION ALL
SELECT
B.guid_id AS Id
, B.user_document AS Document
FROM TableB B
WHERE
B.guid_user_id = 'valid guid in here'
It works when I run it and it brings the results I need. The column types matches as well. And I got a class like this on this C# project:
using System;
namespace MyProject.Domain.Entities
{
public class UserDocument
{
public Guid? Id;
public string Document;
}
}
For my DbContext, I got this class:
...
public class MyDbContext : DbContext
{
private readonly IHostingEnvironment _env;
public MyDbContext(IHostingEnvironment env)
{
_env = env;
}
... some DbSets in here that are working fine ...
public DbQuery<UserDocument> UserDocuments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
... a couple "modelBuilder.ApplyConfiguration(config instance);" for the DbSets ...
base.OnModelCreating(modelBuilder);
}
}
On my repository class:
public IEnumerable<UserDocument> GetUserDocuments(string accountId)
{
string query = $@"SELECT
A.guid_id AS Id
, A.document AS Document
FROM TableA A
WHERE
A.guid_user_id = '{accountId}'
UNION ALL
SELECT
B.guid_id AS Id
, B.user_document AS Document
FROM TableB B
WHERE
B.guid_user_id = '{accountId}';";
#pragma warning disable EF1000 // Possible SQL injection vulnerability, I know, but it is just for testing.
return Db.UserDocuments.FromSql(query).ToList(); // Db holds an instance of MyDbContext
#pragma warning restore EF1000
}
It runs and returns the right amount of objects that it was supposed to, but all of them get properties with null values!
Am I missing something?
I'm looking for a way of getting the expected result without having to create a DbSet for both TableA and TableB to create the union. Is there any way of doing that?
Everything is working great with my DbSets, but this DbQuery is just not working.
Upvotes: 0
Views: 1745
Reputation: 125
I just forgot to add getters and setters to the model. It just look like this to be working:
using System;
namespace MyProject.Domain.Entities
{
public class UserDocument
{
public Guid? Id { get; set;}
public string Document { get; set;}
}
}
Upvotes: 2