小编Mat*_*ger的帖子

声明类型中的网址是什么

由于我想向应用程序中添加自定义声明,因此我检查了ClaimTypes的源代码(由JetBrains反编译器反编译)。这是其中的一部分:

namespace System.Security.Claims
{
  /// <summary>Defines constants for the well-known claim types that can be assigned to a subject. This class cannot be inherited.</summary>
  [ComVisible(false)]
  public static class ClaimTypes
  {
    internal const string ClaimTypeNamespace = "http://schemas.microsoft.com/ws/2008/06/identity/claims";
    /// <summary>The URI for a claim that specifies the instant at which an entity was authenticated; http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant.</summary>
    public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant";
    /// <summary>The URI for a claim that specifies the method with which an entity was authenticated; http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod.</summary>
    public const string AuthenticationMethod …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc authorization claims-based-identity

6
推荐指数
1
解决办法
1855
查看次数

用roslyn扩展c#语法

我试图在没有else的情况下实现"return if"/"return value if",因为我只想在条件有效时返回或返回值.

我知道,有if (condition) return;或者if (condition) return value;我想让代码更清洁一点,因为它更具可读性,所以拥有这种语法会很好.

我听说过roslyn这是可能的,并在这里回答问题:有没有办法在C#中实现自定义语言功能?但我不知道如何实现它.

所以代码将是这样的:

public class Testclass
{
    public static void Main(String[] args)
    {
        Testclass t = new Testclass();
        t.TestMyClassWithVoid();
        bool success = t.TestMyClassWithInt(3) == 3;
        bool fail = t.TestMyClassWithInt(2) == 2;
    }

    public void TestMyClassWithVoid()
    {
        int value = GetValueFromSomeWhere();
        return if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
    }

    public int TestMyClassWithInt(int value)
    {
        return value if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

任何想法我怎么能解决这个问题?我开始尝试使用Roslyn.Compilers.CSharp …

c# roslyn

5
推荐指数
1
解决办法
996
查看次数

迭代字典时的 hasOwnProperty

我对 javascript 很陌生,我正在尝试迭代字典键/值。(是的,我在这里读了一些帖子,但没有找到答案。)

这是我的字典:

showhidedict = {
    0: ["a"],
    1: [],
    2: ["a", "b"],
    3: []
};
Run Code Online (Sandbox Code Playgroud)

这是我的迭代:

for (var value in showhidedict)
    $("#" + showhidedict[value]).hide();
Run Code Online (Sandbox Code Playgroud)

resharper 建议我将 -check 添加 hasOwnProperty 到循环中:

if (showhidedict.hasOwnProperty(value))
Run Code Online (Sandbox Code Playgroud)

但为什么?

-check hasOwnProperty 检查对象是否具有属性(这里是字典是否包含键),对吗?但我真的需要支票吗?由于我迭代了键,我知道所有键都必须存在。还有其他原因需要添加支票吗?

javascript resharper

5
推荐指数
1
解决办法
1645
查看次数

关闭分配的含义和问题

我正在使用JetBrains Rider进行C#编程,并且我猜想在使用ReSharper时也会出现此警告:

我写了这个函数GetTicket

public async Task<IEnumerable<Ticket>> GetTicket(int id)
{
    return await _memoryCache.GetOrCreateAsync(_cachingFunctionalty.BuildCachingName(id), entry =>
    {
        entry.SlidingExpiration = TimeSpan.FromSeconds(10);
        return GetTicket_uncached(id);
    });
}
Run Code Online (Sandbox Code Playgroud)

GetTicket_uncached,它称为:

private async Task<IEnumerable<Ticket>> GetTicket_uncached(int id)
{
    RestClient client = new RestClient(ServiceAdress);
    Request req = new Request
    {
        Method = Method.GET,
        Resource = "api/tickets/get",
        Parameters = new {ident = id}
    };

    return await client.ExecuteRequestAsync<Ticket[]>(req);
}
Run Code Online (Sandbox Code Playgroud)

因此,id方法中的参数public async Task<IEnumerable<Ticket>> GetTicket(int id)突出显示,并显示以下警告:

关闭分配:“ id”参数和“ this”参考

在谷歌搜索时发现了一些东西,但我仍然不知道这意味着什么,这是什么问题?

c# resharper rider

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

在 SQLModel 中使用表名动态设置 sql-default 值

我正在尝试在 SQLModel 中创建一个基类,如下所示:

class BaseModel(SQLModel):
    @declared_attr
    def __tablename__(cls) -> str:
        return cls.__name__

    guid: Optional[UUID] = Field(default=None, primary_key=True)

class SequencedBaseModel(BaseModel):
    sequence_id: str = Field(sa_column=Column(VARCHAR(50), server_default=text(f"SELECT '{TABLENAME}_' + convert(varchar(10), NEXT VALUE FOR dbo.sequence)")))
Run Code Online (Sandbox Code Playgroud)

所以我得到了一个这样的表:

class Project(SequencedBaseModel):
    ...
Run Code Online (Sandbox Code Playgroud)

Project其中 alembic 将为包含列guid和的表生成迁移sequence_id。序列 ID 的默认值是使用以下命令生成的序列

SELECT '{TABLENAME}_' + convert(varchar(10), NEXT VALUE FOR dbo.sequence)
Run Code Online (Sandbox Code Playgroud)

并且应该将值Project_1, ,Project_2插入到项目表中...

关于如何动态设置表名有什么想法吗?我无法使用构造函数来设置列,因为 alembic 忽略它们,我无法访问该__tablename__()函数,或者cls,因为列是静态的...

python sqlalchemy alembic sqlmodel

5
推荐指数
1
解决办法
1245
查看次数

信封 Odata 响应

我将 Odata 添加到我的项目中,以便我可以使用 url-query-parameters,例如$filter. 使用演示类/控制器,输出现在如下所示:

{
  "@odata.context": "https://localhost:5001/api/v1/$metadata#WeatherForecast",
  "value": [
    {
      "Id": 1,
      "Date": "2021-05-22T14:00:18.9513586+02:00",
      "TemperatureC": 36,
      "Summary": "Sweltering"
    },
    {
      "Id": 2,
      "Date": "2021-05-23T14:00:21.6231763+02:00",
      "TemperatureC": 44,
      "Summary": "Chilly"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,效果很好。

使用我的 API 的前端团队现在想要像信封这样的东西..(是这样称呼的吗?)他们想要得到这样的结果:

{
    "data": {
        "type": "WeatherForecast",
        "count": 2,
        "items" : [
            {
              "Id": 1,
              "Date": "2021-05-22T14:00:18.9513586+02:00",
              "TemperatureC": 36,
              "Summary": "Sweltering"
            },
            {
              "Id": 2,
              "Date": "2021-05-23T14:00:21.6231763+02:00",
              "TemperatureC": 44,
              "Summary": "Chilly"
            }
        ]
    },
    "error": null
}
Run Code Online (Sandbox Code Playgroud)

我有办法做到这一点吗?直接使用 OData 还是以其他方式?我不能简单地更改返回类型,因为 OData 需要 aIQueryable<> …

c# envelope odata .net-5

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

为字符串连接两个对象创建表达式树

我正在学习Expression和他们的表达树一起使用它们与IronPython(但现在这无关紧要).

我要做的是,创建一个表达式树,如下面的lambda:

Func<T, int, string> func = (s,t) => s + t;
Run Code Online (Sandbox Code Playgroud)

我目前的功能是这样的:

public static Expression<Func<T, int, string>> StringConcatSelector<T>()
{
    var parameterParam = Expression.Parameter(typeof(T), "x");
    var paramToString = typeof(T).GetMethods().FirstOrDefault(s=>s.Name=="ToString");
    var parameter = Expression.Call(parameterParam, paramToString);


    var intParameterParam = Expression.Parameter(typeof(int), "s");
    var intParameterToString = typeof(int).GetMethods().FirstOrDefault(s => s.Name == "ToString");
    var intParameter = Expression.Call(intParameterParam, intParameterToString);

    var stringConcat = typeof(string).GetMethods().FirstOrDefault(s => s.Name == "Concat");

    var result = Expression.Call(stringConcat, parameter, intParameter);

    return Expression.Lambda<Func<T, int, string>>
                         (result, parameterParam, intParameterParam);
}
Run Code Online (Sandbox Code Playgroud)

Expression.CallString.Concat …

.net c# lambda expression-trees

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

实体框架7中的AddOrUpdate

我正在尝试实现自己的,AddOrUpdate因为Entity Framework暂时不包含此功能.(我需要它)

我知道这里有类似的问题,但要么没有答案,要么是另一个问题.

所以,我在尝试实现更新部分时遇到困难.这是我的代码:

  • @this:我在数据库中输入的DbSet
  • 参数:在DB中检查是否输入的属性已存在
  • 条目:要添加或更新的所有条目

public static void AddOrUpdate<T>(this DbSet<T> @this, Func<T, object> parameter, params T[] entries) where T: class, IEntity
{
    IEnumerable<object> keysExisting = @this.Select(parameter);

    foreach (T entry in entries)
    {
        bool entryExistsAlready = keysExisting.Contains(parameter.Invoke(entry));
        if (!entryExistsAlready)
        {
            @this.Add(entry);
            return;
        }
        entry.Id = @this.First(w => parameter.Invoke(w).Equals(parameter.Invoke(entry))).Id;
        @this.Attach(entry);
        @this.Update(entry);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了完成信息,这就是我调用方法的方法(已经有一个ApplicationUser存储在数据库中,电子邮件"test@test.de"):

db.ApplicationUsers.AddOrUpdate(s => s.Email,
        new ApplicationUser{Email="test@test.de", Attribute="modified attribute"}
        );
Run Code Online (Sandbox Code Playgroud)

我尝试附加条目而不附加.我总是得到以下异常(Attach()或者,当没有附加时,在Update():

InvalidOperationException:无法跟踪实体类型"ApplicationUser"的实例,因为已经跟踪了具有相同键的此类型的另一个实例.添加新实体时,对于大多数键类型,如果未设置任何键,则将创建唯一的临时键值(即,如果为键属性指定了其类型的默认值).如果要为新实体显式设置键值,请确保它们不会与现有实体或为其他新实体生成的临时值发生冲突.附加现有实体时,请确保只有一个具有给定键值的实体实例附加到上下文.

任何想法,我如何更新我的条目?

更新:

我已经尝试过反射,只是设置每个属性的所有值,但ApplicationUser例如具有Role不可写的属性.所以我的方法调用会丢失数据.

c# entity-framework

0
推荐指数
1
解决办法
1326
查看次数

chararray的大小和长度是不一样的

我已经有了几年的Python,C#和Java经验,我刚开始学习C语言.

我在教程中学到了,这char anything[]总是一个指针.(今天有人告诉我这是错的) - 我认为我的问题与此有关.不过,我正在尝试获取char数组的长度:

#include <stdio.h>

int get_string_length(char * string)
{
    int length = 0;
    while(string[length] != '\0')
    {   
        char c = string[length];
        length++;
    }
    return length;
}

int get_string_size(char * string)
{
    return sizeof(string);
}

int main()
{
    printf("%d\n", get_string_size("hello world")); // returns 8
    printf("%d\n", get_string_length("hello world")); // returns 11
    printf("%d\n", sizeof("hello world")); // returns 12 -> Okay, because of '\0'-char
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

8

11

12

那么,为什么我的get_string_size方法会返回8而不是12?(因为两者都只打电话sizeof())

c arrays

0
推荐指数
1
解决办法
255
查看次数

EF Core生成具有无效表名的语句

我正在尝试使用Include和获取一些值,ThenInclude但是EF Core生成的表名无效的语句。

这是我的DataContext:

public class BaseContext : BaseDbContext 
{
    protected BaseWebsiteContext(DbContextOptions dbContextOptions) : base(dbContextOptions)
    {
    }

    public DbSet<Image> Images { get; set; }
    public DbSet<Tag> Tags { get; set; }
    public DbSet<ImageTags> ImageTags { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的三个数据模型:

public class Image : Entity.Entity
{
    public string Title { get; set; }
    public string Filepath { get; set; }
    public DateTime CreateDate { get; set; }

    public ICollection<ImageTags> ImageTags { get; set; } = new List<ImageTags>(); …
Run Code Online (Sandbox Code Playgroud)

c# sqlexception entity-framework-core

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