必须是不可为空的才能用作参数'T'

use*_*730 6 .net c# entity-framework code-first

我正在尝试使用自己的对象类型创建Code First类并获取此错误:

.MTObject'必须是不可为空的值类型才能在泛型类型或方法' System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration<TStructuralType>.Property<T>(System.Linq.Expressions.Expression<System.Func<TStructuralType,T>>)' 中将其用作参数'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
Run Code Online (Sandbox Code Playgroud)

Sla*_*uma 3

为了让这一行编译...

Property(p => p.Age).HasColumnName("AGE").IsOptional();
Run Code Online (Sandbox Code Playgroud)

...您需要使该Age属性可为空:

public Nullable<Int32> Age { get; set; }
Run Code Online (Sandbox Code Playgroud)

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

或者您无法将该属性指定为可选属性,而需要将其用作必需属性。

编辑

我上面的回答是错误的。这不是编译器错误的原因。但Age如果该属性应该是可选的(即允许null值),则该属性仍然必须可为空。

编辑2

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

Property(p => p.Name.Object).HasColumnName("NAME");
Run Code Online (Sandbox Code Playgroud)

(假设您实际上想要指定Object属性的列名)IsOptional()不需要使用 is ,因为string默认情况下属性是可选的。

  • 另外,“Name”是一个引用类型;它不直接映射到 SQL 类型,因此它应该是一个导航属性。那么它总是可选的。 (2认同)