更新时间:2022-05-17 03:26:39
有一个约束条件:
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?
约束会通知编译器有关类型参数的功能 一定有.没有任何约束,类型参数可以是任何 类型.编译器只能假定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; }