小编Lau*_*oun的帖子

List.Add()的问题仅保存最后添加的项目

我注意到的问题是这行代码:

tempList.Add(orderables);
Run Code Online (Sandbox Code Playgroud)

在这个完整的代码中:

AssociatedComboItems ai = new AssociatedComboItems();
List<Orderables> tempList = new List<Orderables>();
Orderables orderables = new Orderables();

foreach (var t in comboBox1.Items)
{
    ai.ComboBoxItem = t.ToString();

    for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++)
    {
        orderables.Display = fpSpread1.ActiveSheet.Cells[i, 1].Text;
        orderables.ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value;
        orderables.DisplayOrder = i;
        tempList.Add(orderables);
    }

    ai.AssociatedItems = tempList;
    tempList.Clear();
    if(AssociatedItems == null)
    AssociatedItems = new List<AssociatedComboItems>();
    AssociatedItems.Add(ai);
}
Run Code Online (Sandbox Code Playgroud)

当我将断点放在上面提到的那一行(tempList.Add(orderables);)时,它第一次正确地将项添加到templist它,它将有一个项目.第二次它会将正确的项目添加到列表中但是如果我将鼠标悬停在tempList想要查看其内容的位置,虽然它有两个项目,但它们都是相同的 - 它们现在都是添加到列表中的第二个项目.它覆盖了第一个.

我无法弄清楚这有什么问题,为什么会发生这种情况.

c#

3
推荐指数
1
解决办法
4744
查看次数

如何在 AutoMapper 中添加自定义逻辑?

我有以下代码。
所有字段都很好地从源对象映射到目标对象。
但是,我需要计算目标对象中的一个字段。

例如:
DestinationObj.Status可以根据SourceObj.

如果我要编写代码,它看起来类似于:

foreach (var rec in listData)
{
    string status;

    if (!String.IsNullOrEmpty(rec.Field1))
    {
        status = "Stage 1";
    }

    if (!String.IsNullOrEmpty(rec.Field2))
    {
        status = "Stage 2";
    }

    if (!String.IsNullOrEmpty(rec.Field3))
    {
        status = "Stage 3";
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以在 AutoMapper 中做类似的事情吗?

var config = new MapperConfiguration(c =>
{
    c.CreateMap<SourceObj, DestinationObj>()
        .ForMember(x => x.Status, m => m.MapFrom([Not sure at this point]));
});
Run Code Online (Sandbox Code Playgroud)

编辑:

List<destinationObj> destinObj = new List<destinationObj>();

foreach (var rec in listSourceObject)
{
    destinationObj do = …
Run Code Online (Sandbox Code Playgroud)

c# automapper

3
推荐指数
1
解决办法
6476
查看次数

如何使用POSTMAN发布字符串数组?

我正在使用POSTMAN将字符串数组发送到web api.Web API方法看起来像

[HttpPost]
public async Task<IEnumerable<DocumentDTO>> GetDocuments([FromBody]IEnumerable<string> documentNames)
{
    return await _service.GetDocuments(documentNames);
}
Run Code Online (Sandbox Code Playgroud)

我在这里看到了如何使用邮递员发送数组的SO帖子.所以我在这里发送数组 在此输入图像描述

Fiddler显示请求的内容类型是 multipart/form-data;

在此输入图像描述

但我得到错误回复

{"消息":"请求实体的媒体类型'多部分/格式数据’不支持该资源.","ExceptionMessage":"否MediaTypeFormatter是提供给读IEnumerable类型的"对象1格式化器,IFormatterLogger formatterLogger,的CancellationToken的CancellationToken个)\ r \n在System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage请求,类型类型,IEnumerable`1格式化,IFormatterLogger formatterLogger,的CancellationToken的CancellationToken)"}1' from content with media type 'multipart/form-data'.", "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
"StackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable

我曾尝试设置键documentNames,documentNames[],documentNames[0]
我曾尝试选择身体x-www-form-urlencoded.当我这样做时,API接收空集合.
我尝试选择body作为raw我这样做API接收null作为参数.

问题
1>如何使用表单数据发送字符串数组?
1>如何使用x-www-form-urlencoded发送字符串数组.?
2>如何将字符串数组作为原始json发送?

c# asp.net-web-api postman

3
推荐指数
3
解决办法
1万
查看次数

依赖注入.NET Core-InvalidOperationException

我正在学习.NET Core,并且试图IServiceCollection在startup.cs中使用它来解决我的依赖关系。我在控制器中注入了依赖关系,并且依赖关系被解析为也具有依赖关系的类。基本上我得到了,InvalidOperationException因为它无法激活依赖关系。

这是我的堆栈跟踪:

InvalidOperationException: Unable to resolve service for type 'TestApplication.Services.LoginHttpService' while attempting to activate 'TestApplication.Services.LoginService'.

    Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet<Type> callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)   

    Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet<Type> callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet<Type> callSiteChain)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet<Type> callSiteChain)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet<Type> callSiteChain)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider)
    System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd<TKey, TValue, TArg>(ConcurrentDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg arg)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
    Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
    lambda_method(Closure , IServiceProvider , Object[] …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection inversion-of-control asp.net-core-mvc asp.net-core

3
推荐指数
2
解决办法
1万
查看次数

C#跳过第一行,但希望它跳过最后一行

不确定这是否是最好的方法,但到目前为止这是我的代码.目前,它保留第一个副本并从表中删除其他副本.我希望它保留最后一行的最大OrderId数字并删除其余部分.我试过Take而不是Skip但似乎无法让它正常工作.

var duplicateRow = (from o in db.Orders
                    group o by new { o.CustomerId } into results
                    select results.Skip(1)
                    ).SelectMany(a => a);

db.Orders.DeleteAllOnSubmit(duplicateRow);
db.SubmitChanges();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

c# linq

3
推荐指数
1
解决办法
60
查看次数

在哪里放入InternalsVisibleTo

与此问题相关的是,AssemblyInfo的生成如何工作?

我一直在放入InternalsVisibleTo程序集的第一类文件,我意识到它会很有用.使用其他程序集属性在AssemblyInfo中似乎更合适,但我不希望它被无意中覆盖.

那么,它应该去哪里?

c# assemblies visual-studio

2
推荐指数
3
解决办法
1437
查看次数

如何在C#中将匿名类型转换为IQueryable <Order_Detail>?

我正在创建一个OData方法,其中我编写了以下代码

[WebGet]
public IQueryable<Order_Detail> getByYear(int year)
{
    var dc = new NorthwindBigEntities();
    var query = from p in dc.Order_Details
                where p.Order.OrderDate != null && p.Order.OrderDate.Value.Year == year
                select new
                {
                    TotalSales = p.UnitPrice * p.Quantity,
                    Product = p.Product.ProductName
                };
    return query;
}
Run Code Online (Sandbox Code Playgroud)

但我得到一个例外

无法将类型'System.Linq.IQueryable AnonymousType#1'隐式转换为'System.Linq.IQueryable CustomMethod.Order_Detail'.

我怎么能完成这个?

c# wcf odata

2
推荐指数
1
解决办法
5953
查看次数

将网址写入Razor中的自定义路线

我已声明类似于以下内容的自定义路由:没有“详细信息”操作的ASP.MVC路由

这是我的路线:

routes.MapRoute(
    name: "Profile",
    url: "Profile/{aScreenName}",
    defaults: new { controller = "Profile", action = "Index", aScreenName = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

我以为这看起来更整洁,但现在我正在努力寻找一种方法来创建指向Razor中这些路线的超链接。问题是我尝试的所有对象都需要一个对象,并自动尝试将其视为完整的查询字符串。我找不到合适的助手来做到这一点。我曾尝试@html@url@href

有人知道最好的方法吗?

parameters url asp.net-mvc html.actionlink razor

2
推荐指数
1
解决办法
4404
查看次数

在 EF Core 中添加迁移时出现“实体类型‘CustomAttributeData’需要定义主键”错误

我把我的模型放在一个带有 Core 的类库中。我已经进行了第一次迁移来测试我的模型的一部分,但是在进行了很大的增强之后,我删除了我的数据库和迁移,只有一个 V1 迁移。

问题是,在删除之后,当我尝试出现add-migration此错误时:

System.InvalidOperationException: The entity type 'CustomAttributeData' requires a primary key to be defined.
   at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)
   at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model)
   at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at …
Run Code Online (Sandbox Code Playgroud)

c# ef-code-first entity-framework-core asp.net-core

2
推荐指数
2
解决办法
3528
查看次数

ASP.NET Core 2没有配置身份验证处理程序来处理该方案

我想在ASP.NET Core 2应用程序中提供授权.在账户/登录中发送带有数据的模型后,在调用之后await Authenticate(user),我收到一条错误消息.我无法理解哪里缺乏描述.

Startup.cs

//ConfigureServices
services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie("TmiginScheme", options =>
{
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.ExpireTimeSpan = TimeSpan.FromHours(1);
    options.SlidingExpiration = true;
});

//Configure
app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

的AccountController

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        User user = null;
        Cryptex cryptex = new Cryptex();
        string password = cryptex.EncryptText(model.Password, "TMigin");

        // ???? user
        user = fStorage.Users.GetUserByLogin(model.Login);
        if (user != null)
        {
            if (string.Compare(user.Password, password) != …
Run Code Online (Sandbox Code Playgroud)

c# asp.net authorization asp.net-core

2
推荐指数
2
解决办法
6308
查看次数