2

I'd like to map a one-to-one relationship using Entity Framework 5 Code First like this:

public class User
{
     public Guid Id { get; set; }
}

public class Profile
{
     public User Owner { get; set; }
}

Note that database Profile table schema has a primary key UserId that's a foreign key to Users table.

I'd like to know if I can avoid an artificial identifier in Profiles table.

Thank you in advance!



UPDATE

Well, it seems that both answers of Eranga and hvd are useful. With some own contribution, I got a transaction creating an user with the belonging profile successfully.

  • hvd => There's no need of the artificial identifier in the object model.
  • Erlanga => Your approach works BUT it forces you to have an [Id] column in the database.

Does anyone found a way of avoiding the artificial identifier even in the database table?

4

2 回答 2

3

Use the fluent API to map the relationship.

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entity<Profile>()
        .HasRequired(p => p.Owner)
        .WithOptional();
 }

Update:

One-to-One relationships can only be modeled in using the mapping technique called "Shared Primary Key". That is the PK of the dependent entity is also an FK. There is no artificial identifier involved in the dependent entity(ie. Profile) because it refers to the PK values of independent entity (ie. User)

于 2012-08-02T07:55:45.560 回答
2

This is how I do it (classes renamed to match your situation):

public class User
{
    public Guid Id { get; set; }
    public Profile Profile { get; set; }
}

public class Profile
{
    public Guid OwnerId { get; set; }
    public User Owner { get; set; }
}

var userConfiguration = modelBuilder.Entity<User>();
userConfiguration.HasKey(u => u.Id);
userConfiguration.HasOptional(u => u.Profile).WithRequired(p => p.Owner);

var profileConfiguration = modelBuilder.Entity<Profile>();
profileConfiguration.HasKey(p => p.OwnerId);
profileConfiguration.HasRequired(p => p.Owner).WithOptional(u => u.Profile);

The HasOptional(u => u.Profile).WithRequired(p => p.Owner) tells EF that p.Owner should be mapped to the primary key, which is OwnerId. You should be able to make this work without OwnerId or Profile properties, but this is what works for me, and allows for further configuration of those properties.

于 2012-08-02T09:08:19.723 回答