3

我有一个项目,它有很多数据结构,我想在其中引入一个数据库。我正在研究 Entity Framework CTP5 的代码优先功能。

现在,我为我的每种类型使用了不同的标识符类型(例如 TypeAIdentifier、TypeBIdentifier 等)。这很好,因为它在使用这些标识符时允许类型安全。问题是我似乎无法让 EF 使用非原始类型作为标识符。http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx中有提示:

KeyAttribute 

KeyAttribute is used to specify that a property/column is part of the primary 
key of the entity and applies to scalar properties only. 

实际上,以下程序会引发异常:

class Program
{
    static void Main(string[] args)
    {
        MyDb db = new MyDb();
        db.SaveChanges();
    }
}

class MyDb : DbContext
{
    public DbSet<MyObject> MyObjects { get; set; }
}

class MyObject
{
    [Key] public MyIdentifierType MyId { get; set; }
    public int IntValue { get; set; }
}

class MyIdentifierType
{
    public int UniqueId { get; set; }
}

奇怪的是,这个程序抛出了一个 MissingMethodException (“没有为此对象定义无参数构造函数”),但我确信这与 KeyAttribute 有关,因为以下任一情况都会使程序运行:

  1. 删除[键];或者
  2. 将 [Key] 移动到 IntValue。

如何让 EF 将我的标识符类映射为 PK?想到的两个选项:

  1. 想办法让 EF 使用非原始类型作为 PK。
  2. 将“int”作为 PK 并让 EF 将此“int”转换为 MyIdentifier(这样做的缺点是,如果我决定使用“int”以外的其他东西,我将不得不同时更新 MyIdentifier 和映射,但它至少会让我保持标识符类型的安全性)。我认为 Function Imports 会让我这样做,但它似乎是建立在存储过程之上的。

有没有办法做到这一点?

4

1 回答 1

0

我会将带有属性的键转换为自定义类型。

public class MyObject
{
    public int Id { get; set; }

    public int IntValue { get; set; }

    public MyIdentifierType MyId
    {
        get { return new MyIdentifierType {UniqueId = Id}; } 
        set { Id = value.UniqueId; }
    }
}
于 2011-04-29T20:10:40.073 回答