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

我正在尝试使用自己的对象类型创建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()不是必需的,因为认情况下字符串属性是可选的.

相关文章

C#项目进行IIS部署过程中报错及其一般解决方案_c#iis执行语句...
微信扫码登录PC端网站应用的案例(C#)_c# 微信扫码登录
原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...