linq to sql: 在Entityfamework Core中使用多个DbContext
最近在学习DotNetCore并做一个自己的小项目,分为了多个数据库,AccountDbContext和BlogDbContext,
发blog的时候需要用到Account的信息,但是再Blog中只记录了UserID,然后用到了如下代码:
var q = from u in this.DbAccount.Users
join p in this.DbBlog.Posts
on u.UserID equals p.UserID
select u;
var v = q.FirstOrDefault();
但是目前来说貌似不支持,通过各种搜索,倒是有一个改xml的方案,但是我的项目的DbContext是手写而不是使用SqlMetal工具生成的。报错部分信息如下
"Microsoft.EntityFrame
workCore.Query","queryModel":"(from User u in DbSet<User> join Post p in DbSet<Post> on [u].UserID equals [p].UserID select [u]).F..."}}}}
'q.FirstOrDefault()' threw an exception of type 'System.ArgumentNullException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Value cannot be null.\r\nParameter name: entityType"
ParamName: "entityType"
Source: "Microsoft.EntityFrameworkCore.Relational"
StackTrace: " at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)\r\n at Microsoft.EntityFrameworkCore.RelationalMetadataExtensions.Relational(IEntityType entityType)\r\n at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.RelationalEntityQueryableExpressionVisitor.VisitEntityQueryable(Type elementType)
但是在同一个server上夸数据库的查询再sqlserver和mysql都是支持的。也就是说EFCore 2.0现在不支持,现在临时的解决方案如下,
var userID = this.User.GetUserID();
var queryUsers = from u in this.DbAccount.Users.Include(a => a.Account)
where u.UserID == userID
select new
{
UserID = u.UserID,
UserNickName = u.NickName
};
var queryPosts = from p in this.DbBlog.Posts.Include(a => a.Tags)
join pc in this.DbBlog.PostContents
on p.PostID equals pc.PostID
orderby pc.CreateAt descending
where p.UserID == userID
select new
{
PostID = p.PostID,
UserID = p.UserID,
Title = p.Title,
URL = p.URL,
Summary = p.Summary,
Tags = p.Tags,
EditorType = pc.EditorType,
MD5Hash = pc.MD5Hash,
Content = pc.Content,
ContentCreateAt = pc.CreateAt
};
var queryPo = from u in queryUsers.ToList()
join p in queryPosts.ToList()
on u.UserID equals p.UserID
orderby p.ContentCreateAt
select new
{
UserNickName = u.UserNickName,
Title = p.Title
};
var pa = queryPo.ToList();
测试通过,但是要麻烦多了,就看EFCore什么时候能原生支持了。