简体   繁体   中英

Typed Ids in entity framework

On the client side (WPF or Silverlight for example), I usually model entity ids by creating a id class for each entity:

class CarId { public readonly int Id; ... } // or string or Guid etc

so that I can have strongly typed ids and I won't have to pass around ints (or string or guid) without type information:

class Car { public CarId Id { get; private set; } ... }

(A similar reusable way is to create a generic class Id and have Id).

Being new to entity framework and not having done a lot of back-end work, I wonder, is it possible to have entity framework map typed ids like those to primary key (integer/string/guid) table columns in the db? Initially I'd like to be able to use code-first.

实体框架中的键始终为原始类型-复合键也是如此。

I haven't toyed with this enough yet, but using the technique shown here , you can create strongly typed IDs which are more convenient to use.

abstract class BaseEntity
{
}

abstract class BaseEntityWithID<TEntity> : IPrimaryKey<Guid, TEntity>
{
    public ID<Guid, TEntity> ID
    {
        get;
        set;
    }
}

class TestOne : BaseEntityWithID<TestOne>
{
    public string TestString { get; set; }
}

class TestTwo : BaseEntityWithID<TestTwo>
{
    public string TestString { get; set; }
}

interface IPrimaryKey<T, TEntity>
{
    ID<T, TEntity> ID { get; set; }
}

struct ID<T, TEntity> : IEquatable<ID<T, TEntity>>
{
    readonly T _id;

    public ID(T id)
    {
        _id = id;
    }

    public T Value { get { return _id; } }

    public bool Equals(ID<T, TEntity> other)
    {
        if (_id == null || other._id == null)
            return object.Equals(_id, other._id);

        return _id.Equals(other._id);
    }

    public static implicit operator T(ID<T, TEntity> id)
    {
        return id.Value;
    }

    public static implicit operator ID<T, TEntity>(T id)
    {
        return new ID<T, TEntity>(id);
    }

    //I believe this class also needs to override GetHashCode() and Equals()
}

class Program
{
    static void Main(string[] args)
    {
        var testOneStore = new Dictionary<ID<Guid, TestOne>, TestOne>();
        var testTwoStore = new Dictionary<ID<Guid, TestTwo>, TestTwo>();

        Func<TestOne, TestOne> addTestOne = (entity) =>
        {
            if (entity.ID == Guid.Empty)
            {
                entity.ID = Guid.NewGuid();
            }

            testOneStore.Add(entity.ID, entity);

            return entity;
        };

        Func<TestTwo, TestTwo> addTestTwo = (entity) =>
        {
            if (entity.ID == Guid.Empty)
            {
                entity.ID = Guid.NewGuid();
            }

            testTwoStore.Add(entity.ID, entity);

            return entity;
        };

        var id1 = addTestOne(new TestOne { TestString = "hi" }).ID;
        var id2 = addTestTwo(new TestTwo { TestString = "hello" }).ID;

        Console.WriteLine(testOneStore[id1].TestString); //this line works
        Console.WriteLine(testOneStore[id2].TestString); //this line gives a compile-time error

        Console.ReadKey(true);
    }
}

I haven't used this with Entity Framework yet, but I suspect the BaseEntityWithID<> type will need to mark the ID property as not included in the model, and use a property marked internal to provide value storage. It would be nice if there's a way to get EF to just use the ID<> type, but I haven't looked into this at all.

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