Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架CTP5代码优先:使用非原语类型作为键_C#_Ef Code First_Entity Framework Ctp5 - Fatal编程技术网

C# 实体框架CTP5代码优先:使用非原语类型作为键

C# 实体框架CTP5代码优先:使用非原语类型作为键,c#,ef-code-first,entity-framework-ctp5,C#,Ef Code First,Entity Framework Ctp5,我有一个有很多数据结构的项目,我想在其中引入一个数据库。我正在研究实体框架CTP5的代码优先特性 现在,我正在为我的每个类型(例如TypeAIdentifier、TypeBIdentifier等)使用不同的标识符类型。这很好,因为它允许在使用这些标识符时使用类型安全性。问题是我似乎无法让EF使用非原语类型作为标识符。这里有一个提示: 实际上,以下程序会引发异常: class Program { static void Main(string[] args) { M

我有一个有很多数据结构的项目,我想在其中引入一个数据库。我正在研究实体框架CTP5的代码优先特性

现在,我正在为我的每个类型(例如TypeAIdentifier、TypeBIdentifier等)使用不同的标识符类型。这很好,因为它允许在使用这些标识符时使用类型安全性。问题是我似乎无法让EF使用非原语类型作为标识符。这里有一个提示:

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

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; }
}
类程序
{
静态void Main(字符串[]参数)
{
MyDb=新的MyDb();
db.SaveChanges();
}
}
类MyDb:DbContext
{
公共DbSet MyObjects{get;set;}
}
类MyObject
{
[Key]公共MyIdentifierType MyId{get;set;}
公共int值{get;set;}
}
类MyIdentifierType
{
public int UniqueId{get;set;}
}
奇怪的是,这个程序抛出了一个MissingMethodException(“没有为这个对象定义无参数构造函数”),但我确信这与KeyAttribute有关,因为以下任一情况都会使程序运行:

  • 移除[键];或
  • 将[键]移动到IntValue
  • 如何让EF将标识符类映射为PKs?我想到两个选择:

  • 找出一种让EF使用非原语类型作为PK的方法
  • 将一个“int”作为PK,并让EF将这个“int”转换为MyIdentifier(这有一个缺点,如果我决定使用“int”以外的东西,我必须同时更新MyIdentifier和映射,但它至少可以让我保持标识符类型的安全性)。我原以为函数导入可以让我这样做,但它似乎是建立在存储过程之上的

  • 有没有办法做到这一点?

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

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

    我能够使用CompositeId(x=>x.MyId).KeyProperty(x=>x.UniqueId)在FluentNHibernate中实现这一点。EF CTP5中是否有等效的CompositeId?我找不到。
    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; }
        }
    }