简体   繁体   中英

How to map a property with a complex type to a specific table column with code-first EF 4.3?

I have the following type:

public class Minutes
{        
    public double Value { get; set; }        
}

This type is used in an entity like this:

public class Race
{
    public string Name { get; set; }
    public string Location { get; set; }
    public Minutes TotalMinutes { get; set; }
}

I have a DbContext like this:

public class RaceDataContext:  DbContext
{
    public DbSet<Race> Races { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.ComplexType<Minutes>().Property(x => x.Value);
    }
}

In application development, we've been using an MS-SQL database with no problems. Now, we have to move to the client's Oracle database. The Oracle database has fixed tables with columns that we cannot change. We need to be able to read, update, and insert races. So, I've updated my mapping code to something like this:

public class RaceDataContext:  DbContext
{
    public DbSet<Race> Races { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.ComplexType<Minutes>().Property(x => x.Value);

        modelBuilder.Entity<Race>().Property(x => x.TotalMinutes).HasColumnName("RACEMINUTES"); // <-- ERROR HERE
    }
}

The above code does not compile. It says that TotalMinutes must be a non-nullable value to be used as a parameter of the .Property() method. Here's the actual error from the build output:

The type 'Races.Minutes' 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.Property(System.Linq.Expressions.Expression>)' C:\\Projects\\Races\\RaceDataContext.cs

You were close to the solution.

modelBuilder.Entity<Race>().Property(x => x.TotalMinutes.Value)
   .HasColumnName("RACEMINUTES");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM