[英]Why my string value return as Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String]
When I try to get value of SenderName
and ReceiverName
which are IQueryable<string>
I see string Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String]
on view.当我尝试获取
IQueryable<string>
的SenderName
和ReceiverName
的值时,我看到了字符串Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String]
。
Why I can't see my string
value on db?为什么我在 db 上看不到我的
string
值? Thanks.谢谢。
I am using UnitOfWork
pattern.我正在使用
UnitOfWork
模式。
I can not reach the value of string my model properties我无法达到我的 model 属性的字符串值
using DAL;
using Data.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using TechEnabledSales.Models;
namespace TechEnabledSales.Controllers
{
[Authorize(Roles = "100,200,1000")]
public class InterviewController : Controller
{
private readonly IUnitOfWork _uow;
private readonly ILogger<InterviewController> _log;
public InterviewController(IUnitOfWork uow, ILogger<InterviewController> logger)
{
_uow = uow;
_log = logger;
}
public IActionResult Index()
{
int.TryParse(this.User.FindFirstValue("ClinetId"), out int clientId);
var repo = _uow.GetRepository<Interview>();
var model = new List<InterviewVM>();
model = repo.Single(predicate: f => f.ClientId == clientId)
.Select(s => new InterviewVM
{
SenderId = s.SenderId,
ClientId = s.ClientId,
Id = s.Id,
CreateDate = s.CreateDate,
Message = s.Message,
ReceiverId = s.ReceiverId,
ReceiverName = GetUserName(s.ReceiverId ?? 0),
SenderName = GetUserName(s.SenderId ?? 0)
}).ToList();
ViewBag.Clients = null;
if (this.User.IsInRole("200"))
{
var repoClient = _uow.GetRepository<Clients>();
var clients = repoClient.GetList(size: 2000, orderBy: o => o.OrderBy(o2 => o2.Name)).Items
.Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.Id.ToString()
});
ViewBag.Clients = new SelectList(clients, "Value", "Text", null);
}
return View(model);
}
[HttpPost]
public IActionResult PostMessage(string message, int clientId2 = 0)
{
int.TryParse(this.User.FindFirstValue(ClaimTypes.NameIdentifier), out int userId);
int.TryParse(this.User.FindFirstValue("ClinetId"), out int clientId);
var repo = _uow.GetRepository<Interview>();
var model = new Interview();
model.ClientId = this.User.IsInRole("100") ? clientId : clientId2;
model.Message = message;
model.SenderId = this.User.IsInRole("200") ? userId : 0;
model.ReceiverId = this.User.IsInRole("100") ? userId : 0;
model.CreateDate = DateTime.Now;
repo.Add(model, true);
if (this.User.IsInRole("200"))
return Redirect("/Home/Index");
else
return RedirectToAction("Index");
}
private IQueryable< string> GetUserName(int id)
{
if (id == 0)
return null;
var repo = _uow.GetRepository<Users>();
var model = repo.Single(predicate: u => u.Id == id).Select(s => string.Join(" ", s.FirstName, s.LastName));
return model;
}
}
}
using System;
using System.Collections.Generic;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace DAL
{
public interface IUnitOfWork : IDisposable
{
DbContext GetContext();
List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map);
void ExecuteSql(string query);
IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
IRepositoryAsync<TEntity> GetRepositoryAsync<TEntity>() where TEntity : class;
int SaveChanges();
}
public interface IUnitOfWork<TContext> : IUnitOfWork where TContext : DbContext
{
TContext Context { get; }
}
}
using DAL.Paging;
using Microsoft.EntityFrameworkCore.Query;
using System;
using System.Linq;
using System.Linq.Expressions;
namespace DAL
{
public interface IReadRepository<T> where T : class
{
T Search(params object[] keyValues);
IQueryable<T> Query(string sql, params object[] parameters);
IQueryable<T> Single(Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
bool disableTracking = true);
IPaginate<T> GetList(Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
int index = 0,
int size = 50,
bool disableTracking = true);
IPaginate<TResult> GetList<TResult>(Expression<Func<T, TResult>> selector,
Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
int index = 0,
int size = 50,
bool disableTracking = true) where TResult : class;
}
}
I recommend some changes for your code我建议对您的代码进行一些更改
// ... in InterviewController class
public IActionResult Index()
{
// should check TryParse answer for false value to avoid latest error
int.TryParse(this.User.FindFirstValue("ClinetId"), out int clientId);
var targetClient = this._uow.GetRepository<Interview>()
.Single(predicate: f => f.ClientId == clientId);
// maybe BOOM cause DB don't contains such clientId -- should use try-catch
// maybe should use AutoMapper instead of
var model = new InterviewVM
{
SenderId = targetClient.SenderId,
ClientId = targetClient.ClientId,
Id = targetClient.Id,
CreateDate = targetClient.CreateDate,
Message = targetClient.Message,
ReceiverId = targetClient.ReceiverId,
ReceiverName = GetUserName(targetClient.ReceiverId ?? 0), // maybe should change contract of GetUserName
SenderName = GetUserName(targetClient.SenderId ?? 0)
};
// ...
}
// ...
private string GetUserName(int id)
{
if (id == 0) // What about other extreme values?
{
return null;
}
// should use try-catch
var model = this._uow.GetRepository<Users>()
.Single(predicate: u => u.Id == id);
return $"{model.FirstName} {model.LastName}";
}
}
// ...
public interface IReadRepository<T> where T : class
{
T Search(params object[] keyValues);
IQueryable<T> Query(string sql, params object[] parameters);
T Single(Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
bool disableTracking = true);
// ...
}
private IQueryable< string> GetUserName(int id) { if (id == 0) return null; var repo = _uow.GetRepository<Users>(); var model = repo.Single(predicate: u => u.Id == id).Select(s => string.Join(" ", s.FirstName, s.LastName)); return model; }
According to your code, the GetUserName()
method returns a IQueryable< string>
type value, so, if you directly display the result, it will show EntityQueryable1[System.String]
, instead of the real user name.根据您的代码,
GetUserName()
方法返回一个IQueryable< string>
类型值,因此,如果您直接显示结果,它将显示EntityQueryable1[System.String]
,而不是真实的用户名。
I suggest you could try to change the InterviewVM model as below:我建议您可以尝试更改 InterviewVM model 如下:
public class InterviewVM
{
public string ReceiverName { get; set; }
public string SenderName { get; set; }
//... other properties
}
Then, when you get the user Name, you could use FirstOrDefault().ToString()
method to get the real user name from the IQueryable<string>
result, code like this:然后,当您获取用户名时,您可以使用
FirstOrDefault().ToString()
方法从IQueryable<string>
结果中获取真实的用户名,代码如下:
model =repo.Single(predicate: f => f.ClientId == clientId)
.Select(s => new InterviewVM
{
SenderId = s.SenderId,
ClientId = s.ClientId,
Id = s.Id,
CreateDate = s.CreateDate,
Message = s.Message,
ReceiverId = s.ReceiverId,
ReceiverName = GetUserName(s.ReceiverId ?? 0).FirstOrDefault().ToString(),
SenderName = GetUserName(s.SenderId ?? 0).FirstOrDefault().ToString()
}).ToList();
Besides, on my side, it seems that I can't use the select
clause after Single
method, so, I change the Single
clause to where
clause and use the FirstOrDefault()
method to find the item.另外,在我这边,
Single
方法之后好像不能使用select
子句,所以我把Single
子句改成where
子句,使用FirstOrDefault()
方法查找项目。
code like this:像这样的代码:
public IActionResult Index2()
{
var result = interviews.Where(predicate: u => u.Id == 101).Select(s => new Interview()
{
Id = s.Id,
Message = s.Message,
ReceiverName = GetUserName(s.ReceiverId).FirstOrDefault().ToString(),
SenderName = GetUserName(s.SenderId).FirstOrDefault().ToString()
}).FirstOrDefault();
return View(result);
}
private IQueryable<string> GetUserName(int id)
{
if (id == 0)
return null;
var repo = users;
var model = repo.Where(predicate: u => u.Id == id).Select(s => string.Join(" ", s.FirstName, s.LastName)).AsQueryable();
return model;
}
The result like this:结果是这样的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.