C#泛型错误-类型字符串必须不可为空 [英] C# generics error - The type string must be non nullable

查看:385
本文介绍了C#泛型错误-类型字符串必须不可为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有基于.net core 3.0构建的其余API的通用结构

I have generic structure for my rest API that is built on .net core 3.0

这是我的通用实体代码.

Here is my code for generic entities.

public interface IFullAuditedEntity
{
    object Id { get; set; }
}

public abstract class FullAuditedEntity<T> : IFullAuditedEntity where T : struct
{
    public IFullAuditedEntity() { }

    [Key]
    public virtual T Id { get; set; }

    object Entity.Id
    {
        get { return Id; }
        set
        {
            Id = (T)value;
        }
    }
}

现在,如果我的实体具有 int主键,则此结构对我来说很好用.

Now, this structure works fine for me if my entity has int primary key.

但是如果我必须使用 string作为主键,它会给我泛型错误.参见下面的实体.

But If I have to use string as a primary key, it gives me generics error. see below entity.

[Table(name: "Status")]
public class Status : FullAuditedEntity<string>
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Required]
    [StringLength(03)]
    public override string Id { get; set; }

    [StringLength(03)]
    public string Type { get; set; }

}

有关更多信息,请参见添加的快照.

See added snap for more information.

我试图通过Nullable,如其他一些SO答案所建议的那样,但它对我不起作用,因此,我们将不胜感激任何帮助.

I tried to pass Nullable as some of other SO answers suggested but it didn't work for me, so any help would be really appreciated.

推荐答案

有一个约束条件:

public abstract class Entity<T> : IEntity where T : struct

所以string不是struct的类型,string是引用类型. .NET中的struct和class有什么区别?

so string is not type of struct, string is a reference type. What's the difference between struct and class in .NET?

正如msdn所说:

约束会通知编译器有关类型参数的功能 一定有.没有任何约束,类型参数可以是任何 类型.编译器只能假定System.Object的成员, 是任何.NET类型的最终基类.欲获得更多信息, 请参阅为什么要使用约束条件.

Constraints inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object, which is the ultimate base class for any .NET type. For more information, see Why use constraints.

您可以删除此约束以避免发生此错误,现在您的Id可以是任何类型:

You can remove this constraint to avoid this error and now your Id can be any type:

public abstract class Entity<T> : IEntity

作为string类型的密钥的替代方案,如果它适合您的情况,则可以创建T类型的Guid.如果它可以是Guid类型,则可以避免删除约束:

As an alternative to string type of key and if it is eligible for your case, you can create T type of Guid. If it can be type of Guid, then you can avoid deletion of constraint:

public abstract class FullAuditedEntity<T> : IFullAuditedEntity where T : struct
{
     // ... The code is omitted for the brevity
}

和您的实体:

[Table(name: "Status")]
public class Status : FullAuditedEntity<string>
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Required]
    [Guid]
    public override Guid Id { get; set; }

这篇关于C#泛型错误-类型字符串必须不可为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆