【问题标题】:One to one relation with EF 4.1 code first首先与 EF 4.1 代码的一对一关系
【发布时间】:2011-06-11 05:54:41
【问题描述】:

我的问题和这个类似:

--> Many to one configuration using EF 4.1 code first

google 上有一些流畅的 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; }
}

【问题讨论】:

标签: entity-framework-4.1 code-first one-to-one


【解决方案1】:

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

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

过去这对我来说效果很好。

【讨论】:

  • 奇怪。我又试了一遍,现在可以了:)
  • @Michal B 您使用的 EF 版本与您当时使用的版本相同吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多