如何在对EF上下文进行查询时结合Find()
使用AsNoTracking()
以防止跟踪返回的对象.这是我不能做的
_context.Set<Entity>().AsNoTracking().Find(id);
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我使用EF版本6.
注意:我不想使用SingleOrDefault()
,或Where
.我只是不能,因为参数Id
是通用的,它是一个struct
,我不能==
在这种情况下应用泛型运算符.
我有以下方法:
void Method(string param1, string param2);
void Method(string param1, object param2);
Run Code Online (Sandbox Code Playgroud)
当我使用以下方法调用该方法时:
method("string", null);
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误,因为调用是模糊的,编译器不知道要调用哪个版本,因为两个方法都接受null
作为第二个参数.
如何在不更改其中一个方法名称的情况下克服此问题?第一种方法永远不会有null
.
在我的缓存AddItem
和GetItem
方法中,我在继续之前检查到 redis 的连接是否处于活动状态,是ConnectionMultiplexer.IsConnected
一个昂贵的方法调用吗?或者我应该在这种情况下捕获异常并重新连接?
我有这个扩展方法:
public static IQueryable<T> FilterByEmployee<T>(this IQueryable<T> source, EmployeeFilter filter)
where T : class, IFilterableByEmployee
{
if (!string.IsNullOrEmpty(filter.Gender))
source = source.Where(e => e.Employee.Gender == filter.Gender);
if (!string.IsNullOrEmpty(filter.NationalityID))
source = source.Where(e => e.Employee.NationalityID == filter.NationalityID);
// filter the group
if (filter.IncludeChildGroups)
{
var groups = Security.GetAllChildGroups(filter.GroupID);
source = source.Where(e => e.Employee.EmployeeGroupID.HasValue
&& groups.Contains(e.Employee.EmployeeGroupID.Value));
}
else
{
source = source.Where(e => e.Employee.EmployeeGroupID == filter.GroupID);
}
// filter status
if (filter.OnlyActiveEmployees)
source = source.Where(e => e.Employee.Status == "Active");
return source;
}
Run Code Online (Sandbox Code Playgroud)
和另一个完全相同,但它Employees
直接过滤上下文: …
我想先将代码优先项目转换为数据库。有没有一种自动的方法,还是应该只删除实体和上下文代码并从创建的数据库中创建模型?
如果我有一个div
with overflow: visible;
,我可以让溢出文本的颜色与里面的文本颜色不同div
吗?
像这样(黑框是 div):
<div style="overflow: visible; max-width: 200px;">
Text will for sure overflow
</div>
Run Code Online (Sandbox Code Playgroud)
我有以下内容
DateTime today = DateTime.Today; // or DateTime.UtcNow.Date;
Run Code Online (Sandbox Code Playgroud)
现在,我不能在Linq-EF中做这样的事情因为Date
无法转换为SQL:
context.Records.Where(r => r.CreationDate.Date == today);
Run Code Online (Sandbox Code Playgroud)
所以,我总是这样做:
DateTime dayEnd = today.AddDays(1).AddMilliseconds(-1);
context.Records.Where(r => r.CreationDate >= today && r.CreationDate <= dayEnd);
Run Code Online (Sandbox Code Playgroud)
现在,有没有更好的方法来结束时间DateTime
而不是增加一天然后花一毫秒?
如果我有以下 ISO 日期:
2021-07-05T13:20:00+06:00
Run Code Online (Sandbox Code Playgroud)
如果我调用DateTime.FromISO
它将其转换为机器本地时间,那么我必须解析该字符串并手动设置区域。
如何创建一个DateTime
偏移量为 +06:00 的 luxon 对象(如解析的字符串中所示),而不需要额外的工作?
请注意,我知道我可以使用DateTime.fromISO(isoDate, { zone: 'utc' });
或任何其他区域,但我是否必须真正解析 iso 字符串并手动获取区域才能将其传递给选项{zone: }
?
Distinct()如何在匿名类型的List <>上工作?它会做一个财产比较吗?还是总是返回相同的列表?
例:
List<SomeObject> list;
....
....
var result = list
.Where(i => i.Condition)
.Select(i => new
{
Name = i.Name,
Date = i.Date
});
.Distinct()
.ToList()
Run Code Online (Sandbox Code Playgroud)
请注意,我在匿名类型列表中应用了非重复。