我正在使用EF Core DbFirst方法。我的dbContext是由Scaffold-DbContext命令自动创建的。
我需要将其他DbSet添加到dbContext中,并向dbContext的OnModelCreating方法中添加一些其他代码,但是在删除每个添加的代码的脚手架之后,我必须再次添加它。
我想要做的是创建另一个局部dbContext类,并将受保护的覆盖标记无效OnModelCreating(ModelBuilder modelBuilder)作为局部方法。
但出现错误:
这是一个伪代码:
MyDbContext1.cs-由Scaffold-DbContext生成
public partial class MyDbContext : DbContext
{
public MyDbContext()
{
}
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public virtual DbSet<Client> Clients { get; set; }
protected override partial void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Client>(entity =>
{
// ... some code
}
}
}
Run Code Online (Sandbox Code Playgroud)
MyDbContext2.cs-我每次在脚手架上添加到dbContext中的这段代码:
public partial class MyDbContext
{
public virtual DbSet<JustAnotherEntity> AnotherEntity { get; set; }
protected override partial void OnModelCreating(ModelBuilder modelBuilder)
{ …Run Code Online (Sandbox Code Playgroud) c# entity-framework partial-classes partial entity-framework-core
我将Serilog配置appsettings.json为通过以下方式通过我的应用程序中的tcp 将条目登录到Logstash中asp net core web api:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Network" ],
"MinimumLevel": {
"Default": "Information"
},
"WriteTo:0": {
"Name": "TCPSink",
"Args": {
"uri": "tcp://172.26.48.39:5066"
}
},
"Properties": {
"app_id": "my-service-api",
"index": "my-app-"
}
},
...
}
Run Code Online (Sandbox Code Playgroud)
但是它记录了太多消息。例如,我在令牌控制器中有一个CreateToken操作方法:
[HttpPost]
public ActionResult<string> CreateToken([FromBody] CredentialsModel credentials)
{
var user = _authentication.Authenticate(credentials);
if (user == null)
{
Log.Warning("Unable to authenticate an user: {Login}, {Password}",
credentials.Username, credentials.Password);
return Unauthorized();
}
return BuildToken();
}
Run Code Online (Sandbox Code Playgroud)
我只需要记录一条消息:
无法验证用户的登录密码
但是Serilog记录以下内容:
请求启动HTTP …
我使用实体框架核心 2.1。
我在数据库中有一个标量函数,它添加了指定的天数。我创建了一个扩展方法来执行它:
public static class AdventureWorks2012ContextExt
{
public static DateTime? ExecFn_AddDayPeriod(this AdventureWorks2012Context db, DateTime dateTime, int days, string periodName)
{
var sql = $"set @result = dbo.[fn_AddDayPeriod]('{dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}', {days}, '{periodName}')";
var output = new SqlParameter { ParameterName = @"result", DbType = DbType.DateTime, Size = 16, Direction = ParameterDirection.Output };
var result = db.Database.ExecuteSqlCommand(sql, output);
return output.Value as DateTime?;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试在查询中使用标量函数(为了简化我使用 AdventureWorks2012 的事情),如下所示:
var persons =
(from p in db.Person
join pa in db.Address on p.BusinessEntityId equals pa.AddressId
where …Run Code Online (Sandbox Code Playgroud) 我正在开发ASP .NET Core Web API 2.1应用程序。
我将JWT身份验证服务添加为静态类中的扩展方法:
public static class AuthenticationMiddleware
{
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, string issuer, string key)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
// validate the server that created that token
ValidateIssuer = true,
// ensure that the recipient of the token is authorized to receive it
ValidateAudience = true,
// check that the token is not expired and that the signing key of the issuer is valid
ValidateLifetime = true, …Run Code Online (Sandbox Code Playgroud) 我正在学习ReactJS并遇到以下问题.我有一个联系人搜索输入,并希望在用户停止输入后1000ms内处理它.我为此目的使用去抖功能:
import React, { Component} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {debounce} from 'lodash';
const contacts = [
{
id: 1,
name: 'Darth Vader',
phoneNumber: '+250966666666',
image: 'img/darth.gif'
}, {
id: 2,
name: 'Princess Leia',
phoneNumber: '+250966344466',
image: 'img/leia.gif'
}, {
id: 3,
name: 'Luke Skywalker',
phoneNumber: '+250976654433',
image: 'img/luke.gif'
}, {
id: 4,
name: 'Chewbacca',
phoneNumber: '+250456784935',
image: 'img/chewbacca.gif'
}
];
class Contact extends React.Component {
render() {
return (
<li className="contact">
<img className="contact-image" src={this.props.image} width="60px" …Run Code Online (Sandbox Code Playgroud) 我正在阅读这篇关于Parallel.ForEach“Parallel.ForEach 与传入异步方法不兼容”的文章。
所以,为了检查我写了这段代码:
static async Task Main(string[] args)
{
var results = new ConcurrentDictionary<string, int>();
Parallel.ForEach(Enumerable.Range(0, 100), async index =>
{
var res = await DoAsyncJob(index);
results.TryAdd(index.ToString(), res);
});
Console.ReadLine();
}
static async Task<int> DoAsyncJob(int i)
{
Thread.Sleep(100);
return await Task.FromResult(i * 10);
}
Run Code Online (Sandbox Code Playgroud)
此代码同时填充results字典。
顺便说一下,我创建了一个类型的字典,ConcurrentDictionary<string, int>因为万一我ConcurrentDictionary<int, int>在调试模式下探索它的元素时,我看到元素是按键排序的,我认为因此添加了 elenents。
所以,我想知道我的代码是否有效?如果它“与传入异步方法不兼容”,为什么它运行良好?
我有一个要求,后台服务应该在Process每天凌晨 0:00 运行方法
因此,我的一位团队成员编写了以下代码:
public class MyBackgroundService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public MyBackgroundService(ILogger<MyBackgroundService> logger)
{
_logger = logger;
}
public void Dispose()
{
_timer?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
TimeSpan interval = TimeSpan.FromHours(24);
TimeSpan firstCall = DateTime.Today.AddDays(1).AddTicks(-1).Subtract(DateTime.Now);
Action action = () =>
{
Task.Delay(firstCall).Wait();
Process();
_timer = new Timer(
ob => Process(),
null,
TimeSpan.Zero,
interval
);
};
Task.Run(action);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask; …Run Code Online (Sandbox Code Playgroud) 我正在阅读这篇关于 LINQ 的文章,但无法理解查询是如何在惰性求值方面执行的。
因此,我将文章中的示例简化为以下代码:
void Main()
{
var data =
from f in GetFirstSequence().LogQuery("GetFirstSequence")
from s in GetSecondSequence().LogQuery("GetSecondSequence", f)
select $"{f} {s}";
data.Dump(); // I use LINQPAD to output the data
}
static IEnumerable<string> GetFirstSequence()
{
yield return "a";
yield return "b";
yield return "c";
}
static IEnumerable<string> GetSecondSequence()
{
yield return "1";
yield return "2";
}
public static class Extensions
{
private const string path = @"C:\dist\debug.log";
public static IEnumerable<string> LogQuery(this IEnumerable<string> sequence, string tag, string element …Run Code Online (Sandbox Code Playgroud) 我使用 React Redux 模板创建一个标准 ASP.NET Core 2.1 Web 应用程序。
在“主页”组件中,我想将英语更改为西里尔文字,如下所示:
当我在本地运行它时,此代码呈现如下:
看起来 JSX 没有将文件编译为 UTF8 编码。但我不知道如何检查文件编译后的编码以及如何更改此行为。
你能就此给我建议吗?
更新:
在index.html的head标签中,字符集设置为utf-8:
我需要并行运行三个异步I / O操作,尤其是数据库调用。因此,我编写了以下代码:
// I need to know whether these tasks started running here
var task1 = _repo.GetThingOneAsync();
var task2 = _repo.GetThingTwoAsync();
var task3 = _repo.GetThingThreeAsync();
// await the results
var task1Result = await task1;
var task2Result = await task2;
var task3Result = await task3;
Run Code Online (Sandbox Code Playgroud)
这些GetThingOneAsync(), GetThingTwoAsync(), GetThingThreeAsync()方法彼此非常相似,只不过它们具有不同的返回类型(Task<string>, Task<int>, Task<IEnumerable<int>>)。下面是数据库调用之一的示例:
public async Task<IEnumerable<int>> GetThingOneAsync(string code)
{
return await db.DrType.Where(t => t.Code == code).Select(t => t.IdType).ToListAsync();
}
Run Code Online (Sandbox Code Playgroud)
在调试模式下,我可以看到var task1 = _repo.GetThingOneAsync();开始运行GetThingOneAsync()异步方法(与其他两个任务相同)。
我的同事说,_repo.GetThingOneAsync() …
c# ×6
asp.net-core ×2
async-await ×2
linq ×2
reactjs ×2
.net ×1
.net-4.5 ×1
.net-core ×1
asp.net-core-hosted-services ×1
asynchronous ×1
debounce ×1
debouncing ×1
javascript ×1
jsx ×1
partial ×1
react-redux ×1
redux ×1
serilog ×1
task ×1
timer ×1