2011-06-10 106 views
0

我的问题是类似这样的:一对一与EF 4.1代码首先关系

- >Many to one configuration using EF 4.1 code first

上有谷歌还好流利API解决方案,具有压倒一切“OnModelCreating”方法和手动设置外键选项。但是如果可能的话,我宁愿使用数据注释解决方案。因为我想在编码时使用反转属性。如TypeA对象有一个TypeB对象。所以TypeB对象应该有一个ParentTypeA属性。示例:

public class User : IUser 
{ 
    [Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 

    [RegularExpression(@"[A-Za-z0-9_\-\.]{2,32}"), MinLength(2), MaxLength(32)] 
    [Required(AllowEmptyStrings = false)] 
    public string UserName { get; set; } 

    // other props .... 
    // .... 

    public virtual UserGallery Gallery { get; set; } 
} 

public class UserGallery : IUserGallery 
{ 
    [Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int UserGalleryId { get; set; } 

    // other props .... 
    // .... 

    public virtual User ParentUser { get; set; } 
} 
+0

的可能重复的[如何使用声明一对一的关系实体框架4代码优先(POCO)](http://stackoverflow.com/questions/3622572/how-to-declare-one-to-one-relationship - 使用实体框架-4编码先POCO) – 2013-03-30 10:48:30

回答

1

在Code First中执行此操作的约定方式是使用UserID作为UserGallery对象的主键。这是好的,如果它是一个真正的一对一的关系。

public class UserGallery : IUserGallery 
{ 
    [Key] 
    public int UserId {get;set;} 
    public User User {get;set;} 
    etc... 
} 

这在过去一直很好,我。

+0

不适合我在EF 4.1 ... – 2011-11-09 11:32:35

+0

奇怪现在的工作。我试过所有这一次后,现在它的作品:) – 2012-02-22 15:27:06

+0

@Michal乙你是否使用EF的相同版本,然后呢? – 2012-02-23 10:45:59