简体   繁体   中英

EF 6/7 Complex type as primary key

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?

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
{
}

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