2012-10-13 136 views
1

在客戶端(WPF或Silverlight例如),通過爲每個實體創建ID I類通常模型實體ID:類型化IDS在實體框架

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

,這樣我可以具有強類型id和我不會以圍繞整數(或字符串或GUID)無類型信息:

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

(A類似的可重複使用的方法是創建一個通用的類ID,並有標識)。

作爲新來的實體框架,並沒有做了很多後端工作,我想知道,是否有可能有實體框架圖類型ID像那些主鍵(整數/字符串/ GUID)表列D b?最初我希望能夠使用代碼優先。

回答

0

實體框架中的鍵始終是原始類型 - 對於組合鍵也是如此。

0

我還沒有玩過這個,但是using the technique shown here,你可以創建更加方便使用的強類型ID。

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); 
    } 
} 

我還沒有與實體框架用這個,但我懷疑BaseEntityWithID<>類型將需要標記ID財產不包括在模型中,並使用屬性標記內部提供價值存儲。如果有一種方法可以讓EF只使用ID<>類型,那就太好了,但我沒有看到這一點。