EF 6/7 Complex type as primary key

c# ef-code-first entity-framework entity-framework-6

Question

Refering to this question: EF4.1 Code First Complex Type as primary key

Has this changed since? Or are there possible workarounds other than creating duplicate persistence objects?

1
1
11/17/2014 1:26:27 PM

Accepted Answer

A work around would be implementing PK-related logic in a base class from which you derive your entities.

Edit: quick example based on referenced question

class TestDbContext : DbContext
{
    public DbSet<Voyage> Voyages { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Voyage>()
            .HasKey(v => v.Id);

        base.OnModelCreating(modelBuilder);
    }
}

public class VoyageNumber
{
    private string _number;

    public VoyageNumber() { }

    public string Id
    {
        get
        {
            return _number;
        }
        set
        {
            if( !string.IsNullOrEmpty( _number ) )
            {
                throw new InvalidOperationException("Id already set");
            }

            if( string.IsNullOrEmpty( value ) )
            {
                throw new ArgumentException("Value cannot be null or empty string");
            }

            _number = value;
        }
    }
}

public class Voyage : VoyageNumber
{
}
1
7/2/2015 7:29:43 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow