实体框架CTP5代码优先:使用非基本类型作为密钥 [英] Entity Framework CTP5 Code First: using non-primitive type as key
问题描述
我有一个项目有很多数据结构,我想在其中引入一个数据库。我正在研究实体框架CTP5的代码优先功能。
I have a project which has quite a few data-structures, and I want to introduce a database into it. I'm looking into Entity Framework CTP5's code-first feature.
现在,我为每种类型使用不同的标识符类型(例如TypeAIdentifier,TypeBIdentifier等)。这很好,因为它在使用这些标识符时允许类型安全。问题是我似乎无法使用非原始类型的
作为标识符。
http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in- the-entity-framework-and-code-first.aspx :
Now, I'm using a distinct Identifier type for each of my types (e.g. TypeAIdentifier, TypeBIdentifier, etc.). It's nice because it allows for type safety when working with these identifiers. The problem is that I can't seem to get EF to use a non-primitive-type as an identifier. There's a hint in 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.
Indeed, the following program throws an exception:
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有关,因为以下任何一个都会使程序运行:
Strangely enough this program throws a MissingMethodException ("no parameterless constructor defined for this object"), but I'm sure this is related to the KeyAttribute because either of the following makes the program run:
- 删除[Key];或
- 将[Key]移至IntValue。
如何让EF将我的标识符类映射为PK?想到两个选项:
How can I get EF to map my Identifier classes as PKs? Two options that come to mind:
- 找出一种让EF使用非原始类型作为PK的方法。
- 将'int'作为PK并获取EF将此'int'转换为MyIdentifier(这样做的缺点是,如果我决定使用除'int'以外的其他东西,我将不得不更新MyIdentifier和映射,但它至少会让我保留
标识符类型安全性)。我认为Function Imports会让我这样做,但它似乎是建立在存储过程之上的。
有没有办法实现这个目标?
Is there a way to achieve this?
推荐答案
嗨yairk,
Hi yairk,
欢迎来到EF论坛。
您的问题与CTP5有关,我会帮助您将您的帖子移至EF(预发布)以获得更好的支持,感谢您的理解。
Your question relates to CTP5, I will help you to move your post to EF(Pre-Release) for better supports, thanks for understanding.
祝你有个愉快的一天。
这篇关于实体框架CTP5代码优先:使用非基本类型作为密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!