Byron Sommardahl
Byron Sommardahl

Reputation: 13012

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

Upvotes: 1

Views: 2677

Answers (1)

Eranga
Eranga

Reputation: 32447

You were close to the solution.

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

Upvotes: 5

Related Questions