使用.NET Core 2.2.300和Entity Framework Core 2.2.4。
我在SQL Server数据库中得到了两个具有相似内容的表,所以我写了一个查询:
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'
当我运行它时它会起作用,并且会带来我需要的结果。列类型也匹配。 在这个C#项目中,我得到了一个像这样的类:
using System;
namespace MyProject.Domain.Entities
{
public class UserDocument
{
public Guid? Id;
public string Document;
}
}
对于我的DbContext,我得到了此类:
...
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);
}
}
在我的存储库类中:
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
}
它会运行并返回原本应有的正确数量的对象,但是它们都具有空值的属性!
我想念什么吗?
我正在寻找一种获得预期结果的方法,而不必为TableA和TableB创建DbSet来创建联合。有什么办法吗?
我的DbSet一切正常,但是此DbQuery不能正常工作。
答案 0 :(得分:0)
我只是忘了在模型中添加getter和setter。看起来像这样可以正常工作:
using System;
namespace MyProject.Domain.Entities
{
public class UserDocument
{
public Guid? Id { get; set;}
public string Document { get; set;}
}
}