加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 必须是不可为空的才能用作参数’T’

发布时间:2020-12-15 08:40:38 所属栏目:百科 来源:网络整理
导读:我正在尝试使用自己的对象类型创建Code First类并获取此错误: .MTObject' must be a non-nullable value type in order to use it as parameter ‘T’ in the generic type or method ‘ System.Data.Entity.ModelConfiguration.Configuration.StructuralTy
我正在尝试使用自己的对象类型创建Code First类并获取此错误:

.MTObject' must be a non-nullable value type in order to use it as
parameter ‘T’ in the generic type or method
System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration<TStructuralType>.Property<T>(System.Linq.Expressions.Expression<System.Func<TStructuralType,T>>)

有没有办法声明我的类属性来解决这个错误?

代码如下:

// Simple Example

public class MTObject
{
    public string Object { get; set; }

    public MTObject()
    {

    }
}

public class Person
{
    public decimal Id { get; set; }

    //public string Name { get; set; }

    public MTObject Name { get; set; }

    public Int32 Age { get; set; }
}

public class PersonConfiguration : EntityTypeConfiguration<Person>
{
    public PersonConfiguration() : base()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasColumnName("ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.Name).HasColumnName("NAME").IsOptional();
        Property(p => p.Age).HasColumnName("AGE").IsOptional();
        ToTable("Person");
    }
}

public class PersonDataBase : DbContext
{
    public DbSet<Person> Persons { get; set; }

    public PersonDataBase(string connectionString) : base(connectionString)
    {
        Database.CreateIfNotExists();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new PersonConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}

// End Simple EXample

解决方法

为了得到这一行编译……
Property(p => p.Age).HasColumnName("AGE").IsOptional();

…你需要使Age属性可以为空:

public Nullable<Int32> Age { get; set; }

(或public int?Age {get; set;})

或者您不能将该属性指定为可选属性,并且需要将其用作必需属性.

编辑

我上面的回答是错误的.这不是编译器错误的原因.但是如果Age属性应该是可选的,那么Age属性仍然可以为空,即允许空值.

编辑2

在您的模型中,MTObject是一种复杂类型(不是实体),因为按照惯例,EF无法推断主键属性.对于复杂类型,您可以将嵌套属性映射为:

Property(p => p.Name.Object).HasColumnName("NAME");

(假设您确实要为Object属性指定列名)使用is IsOptional()不是必需的,因为默认情况下字符串属性是可选的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读