EF4.1 как смоделировать отношения 0: 1 (1: 1) - PullRequest
0 голосов
/ 14 мая 2011

Я пытаюсь смоделировать «Пользователь может иметь 0 или 1 набор предпочтений», где таблица предпочтений имеет первичный ключ UserId, который также является внешним ключом для сущности «Пользователь», как это сообщение .

Я хочу, чтобы моя модель была похожа на:

  public class User
  {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int Id { get; set; }

    [Required]
    public virtual string Username { get; set; }

    public virtual UserPreferences Preferences { get; set; }

  }

  public class UserPreferences
  {
    [Key]
    public User User { get; set; }

    public bool SubscribedToNewsLetter{ get; set; }
  }

с настройкой:

HasOptional(u => u.Preferences).WithRequired(l => l.User);

выход:

SetUp : System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation:

    System.Data.Edm.EdmEntityType: : EntityType 'UserPreferences' has no key defined. Define the key for this EntityType.
    System.Data.Edm.EdmEntitySet: EntityType: EntitySet �UserPreferences� is based on type �UserPreferences� that has no keys defined.

Ответы [ 2 ]

1 голос
/ 14 мая 2011

Вы должны определить ключ в UserPreferences:

public class UserPreferences
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserId { get; set; }
    public User User { get; set; }

    public bool SubscribedToNewsLetter{ get; set; }
}
0 голосов
/ 14 мая 2011

Вот то, что я получил в итоге, дает мне именно то, что я искал:

  public class User
  {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int Id { get; set; }

    [Required]
    public virtual string Username { get; set; }

    public virtual UserPreferences Preferences { get; set; }

  }

  public class UserPreferences
  {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }

    [Required]
    public string Password { get; set; }
  }

  public class UserConfiguration : EntityTypeConfiguration<User>
  {
    public UserConfiguration()
    {     
      HasOptional(u => u.Preferences).WithRequired(up => up.User);
    }
  }

public class UserPreferenceConfiguration : EntityTypeConfiguration<UserPreferences>
  {
    public UserPreferenceConfiguration()
    {
      HasRequired(u => u.User).WithOptional(ua => ua.Preferences);
    }
  }

выход:

CREATE TABLE [dbo].[Users](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Username] [nvarchar](max) NOT NULL,
    [DeActivatedDate] [datetime] NULL,
    [IsActive] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[UserPreferences]    Script Date: 05/14/2011 14:36:51 ******/

CREATE TABLE [dbo].[UserPreferences](
    [UserId] [int] NOT NULL,
    [Password] [nvarchar](max) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [UserId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  ForeignKey [User_Preferences]    Script Date: 05/14/2011 14:36:51 ******/
ALTER TABLE [dbo].[UserPreferences]  WITH CHECK ADD  CONSTRAINT [User_Preferences] FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([Id])
GO
ALTER TABLE [dbo].[UserPreferences] CHECK CONSTRAINT [User_Preferences]
GO
...