Tearing my hair out again on this one...using EF 5 Code First, building the model in code - compiles, so it is syntactically correct, but I get an exception when the code builds the model. Here is the entity class (I also have vaidation attributes, but have removed them here for readability):
[Table("USERS")]
public class User : IPEntity
{
#region Constructor (needs to initialize list objects for related entities)
public User()
{
this.Profiles = new List<Profile>();
this.ProfileDivs = new List<ProfileDiv>();
this.ProfileDepts = new List<ProfileDept>();
}
#endregion
#region Entity properties and validation attributes
[Key]
public long UserId { get; set; }
public long PclientId { get; set; }
public string UserName { get; set; }
public string UserDescription { get; set; }
public long? EmpId { get; set; }
public string MustChangePassword { get; set; }
public long? FailedLogins { get; set; }
public DateTime? LastLogin { get; set; }
public long? SequenceNumber { get; set; }
public string AllDivs { get; set; }
public string AllDepts { get; set; }
public string UserRole { get; set; }
public DateTime? BeginSupport { get; set; }
public DateTime? EndSupport { get; set; }
public string OneTimeAccess { get; set; }
public long? ClonedFromUser { get; set; }
public string Email { get; set; }
public string ResetEmail { get; set; }
public DateTime? ResetTimeout { get; set; }
public long? ChallengeFailures { get; set; }
public string PermUserRole { get; set; }
public DateTime? PasswordChangedDate { get; set; }
public virtual ICollection<Profile> Profiles { get; set; }
public virtual ICollection<ProfileDiv> ProfileDivs { get; set; }
public virtual ICollection<ProfileDept> ProfileDepts { get; set; }
public virtual WorkSession WorkSession { get; set; }
}
The model builder class is:
public class User_Map : EntityTypeConfiguration<User>
{
public User_Map()
{
this.ToTable("USERS");
this.HasKey(t => new { t.UserId });
this.Property(t => t.UserId)
.HasColumnName("USER_ID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
.IsRequired();
this.Property(t => t.UserName)
.HasColumnName("USERNAME")
.IsRequired()
.HasMaxLength(25);
this.Property(t => t.PclientId)
.HasColumnName("PCLIENT_ID");
this.Property(t => t.EmpId)
.HasColumnName("EMP_ID");
this.Property(t => t.MustChangePassword)
.HasColumnName("MUST_CHANGE_PASSWORD")
.HasMaxLength(1);
this.Property(t => t.UserDescription)
.HasColumnName("USER_DESCRIPTION")
.HasMaxLength(80);
this.Property(t => t.FailedLogins)
.HasColumnName("FAILED_LOGINS");
this.Property(t => t.LastLogin)
.HasColumnName("LAST_LOGIN");
this.Property(t => t.SequenceNumber)
.HasColumnName("SEQUENCE_NUMBER");
this.Property(t => t.AllDivs)
.HasColumnName("ALL_DIVS")
.HasMaxLength(1);
this.Property(t => t.AllDepts)
.HasColumnName("ALL_DEPTS")
.HasMaxLength(1);
this.Property(t => t.UserRole)
.HasColumnName("USER_ROLE")
.HasMaxLength(2);
this.Property(t => t.BeginSupport)
.HasColumnName("BEGIN_SUPPORT");
this.Property(t => t.EndSupport)
.HasColumnName("END_SUPPORT");
this.Property(t => t.OneTimeAccess)
.HasColumnName("ONE_TIME_ACCESS")
.HasMaxLength(1);
this.Property(t => t.ClonedFromUser)
.HasColumnName("CLONED_FROM_USER");
this.Property(t => t.Email)
.HasColumnName("EMAIL")
.HasMaxLength(60);
this.Property(t => t.ResetEmail)
.HasColumnName("RESET_EMAIL")
.HasMaxLength(60);
this.Property(t => t.ResetTimeout)
.HasColumnName("RESET_TIMEOUT");
this.Property(t => t.ChallengeFailures)
.HasColumnName("CHALLENGE_FAILURES");
this.Property(t => t.PermUserRole)
.HasColumnName("PERM_USER_ROLE")
.HasMaxLength(2);
this.Property(t => t.PasswordChangedDate)
.HasColumnName("PASSWORD_CHANGED_DATE");
this.HasOptional(t => t.WorkSession)
.WithRequired(t => t.User);
// TODO: This is syntactically correct but model blows up!
this.HasMany(t => t.Profiles)
.WithRequired(t => t.User)
.HasForeignKey(t => t.UserId);
}
}
When the model builder class' constructor executes, I get the following exception thrown on the line above (after the comment):
The expression 't => t.User' is not a valid property expression.
The expression should represent a property: C#: 't => t.MyProperty'
VB.Net: 'Function(t) t.MyProperty'.
The Profiles entity is very simple:
[Table("PROFILE")]
public class Profile : IPEntity
{
[Key, Column(Order = 0)]
[ForeignKey("UserId")]
public long UserId { get; set; }
[Key, Column(Order = 1)]
public string FunctionalArea { get; set; }
public int RightsId { get; set; }
public User User;
}
I have been beating on this for two or three days, if anyone can spot my mistake, I would be MOST appreciative!
Thanks,
Peter
UPDATE: I found one bone-headed mistake by reading this post, since I had declared something as a field and not a property...but now I get a different exception which I do not understand:
The navigation property 'UserId' is not a declared property on type 'Profile'.
Verify that it has not been explicitly excluded from the model and that
it is a valid navigation property.
This has me confused as UserId IS a declared property on Profile...?
SECOND UPDATE:
I understand the exception but (since there is no inner exception detail) cannot determine where it is coming from. I changed the User_map class to include:
this.HasMany(t => t.Profiles)
.WithRequired(t => t.User)
.HasForeignKey(t => t.UserId)
.WillCascadeOnDelete(false);
and the Profile_map class to include:
this.HasRequired(t => t.User)
.WithMany()
.HasForeignKey(t => t.UserId)
.WillCascadeOnDelete(false);
Since I have to work with the existing database, I am stuck with the property "UserId" being a foreign key in both tables (in User table it is foreign key for Profiles table, in Profiles table it is foreign key for User table.) I added the .WillCascadeOnDelete(false) to both in case there was some kind of circularity problem. Like I said, I cannot determine which map is blowing things up, the calls to both constructors pass without exception, it is only when the override for OnModelCreating in the context exits that the exception is thrown. Here is the override:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var mbProfile = new Profile_map();
modelBuilder.Configurations.Add(mbProfile);
var mbUser = new User_Map();
modelBuilder.Configurations.Add(mbUser);
base.OnModelCreating(modelBuilder);
}
I know I'm still an EF newbie, but I cannot find the problem (well, haven't yet anyway...)
Thanks again.
public User User;
should be a property instead of a field - like all the others :)
public User User { get; set; }
With virtual preferably (to allow lazy loading), because you have marked all your navigation properties as virtual.
Edit about the UPDATE
The exception talks about a navigation property UserId and complains that it is not a "valid navigation property". Indeed it isn't a valid navigation property. The exception indicates that you possibly have used UserId (instead of User) in the WithRequired method. You should take a closer look at that.
Peter, with regard to your issue with the two "UserId" columns, you said that they were both foreign keys. I don't think you are correct. The User.UserId is marked with [Key] and it is the only one in the User class marked that way. It must be the primary id for the User table. On the Profile class, you have both UserId and FunctionalArea marked with [Key]. This means that the Profile table has a joint primary key, one of which is the foreign key to the User table's UserId column.
That design is perfectly fine. However, in order to have a relationship between User and Profile records where the Profile record is the parent, you would have to have TWO columns on your User table that reference the Profile table's two primary keys, and NEITHER of those columns could be the UserId column of the User table, otherwise you would have a circular dependency with no way of creating either record.
Bottom line is, you don't have two relationships between the User and Profile tables, just one. So delete the following block from your Profile_map class:
this.HasRequired(t => t.User)
.WithMany()
.HasForeignKey(t => t.UserId)
.WillCascadeOnDelete(false);
That should fix it right up! ;)
Related
I have several related domain models that are triggering the exception SqlException: Invalid column name 'ChecklistTemplate_Id'.
My domain model looks like:
public class Assignment
{
public long Id { get; set; }
public long ChecklistId { get; set; }
public DateTime InspectionDate { get; set; }
public long JobId { get; set; }
public Guid? EmployeeId { get; set; }
// TODO: Make the completion a nullable date time in the database and here
public DateTime CompletionDate { get; set; }
public virtual Job Job { get; set; }
public virtual Checklist Checklist { get; set; }
public virtual IList<Image> Images { get; set; }
public virtual IList<Attachment> Attachments { get; set; }
public virtual IList<Equipment> Equipments { get; set; }
}
My EntityTypeConfiguration class looks like:
internal class AssignmentConfiguration : EntityTypeConfiguration<Assignment>
{
public AssignmentConfiguration()
{
ToTable("Assignment");
HasKey(k => k.Id);
Property(a => a.ChecklistId)
.IsRequired();
Property(a => a.CompletionDate)
.IsOptional();
Property(a => a.EmployeeId)
.IsOptional();
Property(a => a.Id)
.IsRequired();
Property(a => a.InspectionDate)
.IsRequired();
Property(a => a.JobId)
.IsRequired();
HasRequired(a => a.Job)
.WithMany(a => a.Assignments)
.HasForeignKey(a => a.JobId);
HasRequired(a => a.Checklist)
.WithOptional(a => a.Assignment);
HasMany(a => a.Images)
.WithRequired(a => a.Assignment)
.HasForeignKey(a => a.InspectionId);
}
}
The Checklist domain model has a ChecklistTemplate navigation property with the join:
HasMany(a => a.CheckLists)
.WithRequired(a => a.ChecklistTemplate)
.HasForeignKey(a => a.ChecklistTemplateId);
There is a one to one between Assignment and Checklist as seen in the Assignment entity configuration.
And yes, we are including the configuration in the DBContext.
Also, I looked at Entity Framework 6 creates Id column even though other primary key is defined and that doesn't seem to apply.
I dont have a satisfactory answer to that but I have had a lot of trouble with ef6. This is because there is a navigation which is not defined or wrongly defined. So ef6 creates it on-the-fly on proxy classes and you cry for hours. I hope you find out the problem soon.
And the navigation you stated is one-to-many. Be careful.
I have trouble understanding why a EF generated SELECT clause contains the primary key twice, the second one is postfixed with '1'.
exec sp_executesql N'SELECT [entity.WebAdminCompanyUser].[CompanyId], [entity.WebAdminCompanyUser].[AspNetUserId], [entity.WebAdminCompanyUser].[CompanyId1]
FROM [SafeProtect].[WebAdminCompanyUser] AS [entity.WebAdminCompanyUser]
INNER JOIN (
SELECT [entity1].[AspNetUserId]
FROM [SafeProtect].[WebAdminUser] AS [entity1]
WHERE ([entity1].[RowEnabled] = 1) AND EXISTS (
SELECT 1
FROM [SafeProtect].[WebAdminCompanyUser] AS [companyUser1]
WHERE ([companyUser1].[CompanyId] = #__companyId_0) AND ([entity1].[AspNetUserId] = [companyUser1].[AspNetUserId]))
) AS [t0] ON [entity.WebAdminCompanyUser].[AspNetUserId] = [t0].[AspNetUserId]
ORDER BY [t0].[AspNetUserId]',N'#__companyId_0 int',#__companyId_0=1
It fails with Invalid column name 'CompanyId1'.
Following are the entities and the corresponding configurations (fluent API):
WebAdminCompanyUser:
public partial class WebAdminCompanyUser : ITrackable, IMergeable
{
public WebAdminCompanyUser()
{
AdditionalInit();
}
public int CompanyId { get; set; }
public int AspNetUserId { get; set; }
public virtual Company Company { get; set; }
[NotMapped]
public TrackingState TrackingState { get; set; }
[NotMapped]
public ICollection<string> ModifiedProperties { get; set; }
[NotMapped]
public Guid EntityIdentifier { get; set; }
partial void AdditionalInit();
}
}
Configuration:
builder.Entity<WebAdminCompanyUser>(entity =>
{
entity.ToTable(name: "WebAdminCompanyUser", schema: SqlSchema.SafeProtect);
entity.HasKey("CompanyId", "AspNetUserId");
entity
.HasOne(d => d.Company)
.WithMany()
.HasForeignKey(d => d.CompanyId)
.IsRequired();
});
WebAdminUser:
public partial class WebAdminUser : IdentityUser<int>, IAuditInfo, IRowDisableableWithDateTime, ITrackable, IMergeable
{
public WebAdminUser()
{
WebAdminCompanyUser = new HashSet<WebAdminCompanyUser>();
WebAdminUserRole = new HashSet<WebAdminUserRole>();
WebAdminUserClaim = new HashSet<WebAdminUserClaim>();
WebAdminUserLogin = new HashSet<WebAdminUserLogin>();
AdditionalInit();
}
public string DisplayName { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool RowEnabled { get; set; }
public DateTime? DisabledOn { get; set; }
public virtual ICollection<WebAdminCompanyUser> WebAdminCompanyUser { get; set; }
public virtual ICollection<WebAdminUserRole> WebAdminUserRole { get; set; }
public virtual ICollection<WebAdminUserClaim> WebAdminUserClaim { get; set; }
public virtual ICollection<WebAdminUserLogin> WebAdminUserLogin { get; set; }
[NotMapped]
public TrackingState TrackingState { get; set; }
[NotMapped]
public ICollection<string> ModifiedProperties { get; set; }
[NotMapped]
public Guid EntityIdentifier { get; set; }
partial void AdditionalInit();
}
Configuration:
builder.Entity<WebAdminUser>(entity =>
{
entity.ToTable(name: "WebAdminUser", schema: SqlSchema.SafeProtect);
entity.Property(e => e.Id).HasColumnName("AspNetUserId");
// authorize multiple user name
entity.HasIndex((p) => new { p.UserName }).IsUnique(false);
entity
.HasMany(user => user.WebAdminUserClaim)
.WithOne()
.HasForeignKey(userClaims => userClaims.UserId)
.IsRequired();
entity
.HasMany(user => user.WebAdminUserLogin)
.WithOne()
.HasForeignKey(userLogin => userLogin.UserId)
.IsRequired();
entity
.HasMany(user => user.WebAdminUserRole)
.WithOne()
.HasForeignKey(userRole => userRole.UserId)
.IsRequired();
entity
.HasMany(user => user.WebAdminCompanyUser)
.WithOne()
.HasForeignKey(companyUser => companyUser.AspNetUserId)
.IsRequired();
});
EF query:
IQueryable<WebAdminUser> query =
from WebAdminUser user WebAdminUserRepository.All()
.Include(user => user.WebAdminUserRole)
.ThenInclude(userRole => userRole.AspNetRole)
.Include(user => user.WebAdminCompanyUser)
where user.WebAdminCompanyUser.Any(companyUser => companyUser.CompanyId == companyId)
select user;
return query.ToList();
Any help appreciated.
This usually happens when you have improperly mapped relationship by leaving some navigation property out of fluent configuration.
Remember that each navigation property (collection or reference) represents a relationship. If you fluently configure relationships and use HasOne / HasMany / WithOne / WithMany w/o passing the navigation property, you are telling EF that the relationship has no navigation property for the corresponding end. But if you actually do have navigation property, EF will map it to a separate relationship with default FK column name. If the default property/column name is already used, EF will append index to it until it gets unique.
In your case, the WebAdminUser class and configuration you've shown are irrelevant. The invalid column name CompanyId1 indicates that the problem is with Company class which you haven't shown, and the WithMany() call here
.HasOne(d => d.Company)
.WithMany() // <--
Most likely your Company class has collection navigation property to WebAdminCompanyUser, something like this (virtual and the name of the property doesn't matter):
public virtual ICollection<WebAdminCompanyUser> CompanyUsers { get; set; }
then you need to change the above .WithMany() call with something like
.WithMany(c => c.CompanyUsers)
and the problem will be solved.
I want to create a Lighthead class that has two one-to-one relationships with the Lens class. When I map the classes as they are set up below I receive the following error.
The operation failed because an index or statistics with name 'IX_Id' already exists on table 'dbo.Lens'.
How do I fix this?
here is my mapping
public class LensMap : EntityTypeConfiguration<Lens>
{
public LensMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Table & Column Mappings
this.ToTable("Lens");
this.Property(t => t.Id).HasColumnName("Id");
// Relationships
this.HasRequired(t => t.LightHead)
.WithOptional(t => t.Lens);
this.HasRequired(t => t.LightHead1)
.WithOptional(t => t.Lens1);
}
}
Here is my lens class
public class Lens
{
public int Id { get; set; }
public virtual LightHead LightHead { get; set; }
public virtual LightHead LightHead1 { get; set; }
}
Here is my lighthead class
public class LightHead
{
public int Id { get; set; }
public virtual Lens Lens { get; set; }
public virtual Lens Lens1 { get; set; }
}
Note I am using Entity Framework 6 and C#
also I have tried to do this with one LightHead in the Lens class it returns the following error
Schema specified is not valid. Errors: The relationship 'WebApplication2.Models.LightHead_Lens' was not loaded because the type 'WebApplication2.Models.Lens' is not available.
I believe you need a foreing key here.
// Relationships
this.HasRequired(t => t.LightHead)
.WithOptional(t => t.Lens)
.HasForeignKey(t => t.LightHeadId)
this.HasRequired(t => t.LightHead1)
.WithOptional(t => t.Lens1);
.HasForeignKey(t => t.LightHead1Id)
...
public class Lens
{
public int Id { get; set; }
public int LightHeadId {get;set;}
public int LightHead1Id {get;set;}
public virtual LightHead LightHead { get; set; }
public virtual LightHead LightHead1 { get; set; }
}
public class LightHead
{
public int Id { get; set; }
public virtual Lens Lens { get; set; }
public virtual Lens Lens1 { get; set; }
}
Alternatively you can use Entity Framework table splitting feature to map two entities to single table.
This also lets you query part of your table columns as single entity in order to improve performance.
So Your mapping should be as below
modelBuilder.Entity<LightHead>.HasOptional(x=> x.Lens).WithRequired(a=> a.LightHead);
modelBuilder.Entity<LightHead>.HasOptional(x=> x.Lens1).WithRequired(a => a.LightHead1);
modelBuilder.Entity<Lens>().Property(x=> x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
You need to set databaseGeneratedOption to None becuase Id of Lens will be same as Id of LightHead as in one to one relationship you can't have primary keys in secondary tables.
Secondary entity is treated as extension of primary entity.
I am having some trouble with EF6 lazy loading, code first to an existing database.
Here are the Entities that are giving me the issue, I have no idea why it is not working, everything I find online says it should be working.
public class User
{
public long UserId { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Token> Tokens { get; set; }
public virtual ICollection<Business> Businesses { get; set; }
public virtual ICollection<Candidate> Candidates { get; set; }
}
Here is the configuration mappings:
public class Token
{
public long TokenId { get; set; }
public long UserId { get; set; }
public Guid TokenValue { get; set; }
public DateTime ExpirationDate { get; set; }
public virtual User User { get; set; }
}
public TokenMap()
{
this.HasKey(t => t.TokenId);
this.Property(t => t.TokenValue)
.IsRequired();
this.Property(t => t.ExpirationDate)
.IsRequired();
this.ToTable("Tokens");
this.Property(t => t.TokenId).HasColumnName("TokenId");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.TokenValue).HasColumnName("TokenValue");
this.Property(t => t.ExpirationDate).HasColumnName("ExpirationDate");
this.HasRequired(s => s.User)
.WithMany(s=>s.Tokens)
.HasForeignKey(s=>s.UserId);
}
public UserMap()
{
this.ToTable("Users");
this.HasKey(t => t.UserId);
this.Property(t => t.Email)
.IsRequired();
this.Property(t => t.FirstName)
.IsRequired();
this.Property(t => t.LastName)
.IsRequired();
this.HasMany(t => t.Businesses)
.WithMany(set => set.Users)
.Map(m =>
{
m.ToTable("BusinessUser");
m.MapLeftKey("UserId");
m.MapRightKey("BusinessId");
});
this.HasMany(s => s.Tokens)
.WithRequired(s => s.User)
.HasForeignKey(s => s.UserId);
this.HasMany(s => s.Candidates)
.WithOptional(s => s.User)
.HasForeignKey(s => s.UserId);
}
And here is a few snippets from the context:
public DbSet<Token> Token { get; set; }
public DbSet<User> User { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TokenMap());
modelBuilder.Configurations.Add(new UserMap());
}
Whenever I do a SingleOrDefault on the Tokens entity the result' user is null.
Any idea what I am doing wrong? All the data in the database is right, and UserId does have a value.
Here is a more elaborate example of calling:
I am implementing the repository patern.
In the class doing the call' constructor I have:
context = new Consolid8ContextProvider();
uow = new UnitOfWork(context);
And then uow.Tokens.First(u => u.ExpirationDate > DateTime.Now && u.TokenValue == token);
Tokens is my TokenRepository that exposes the Tokens entity, and First is a wrapper for FirstOrDefault.
This results in a token object with all of the properties set except for the User navigation property
So I was using BreezeJS and it overrides your context with it's own settings, part of which is to set LazyLoading and EnableProxiesCreation to false.
So if you want to do queries outside of breeze you either have to implement a different constructor for your breeze provider or setting it per query as Slauma has suggested in the comments of the question.
I'm using Entity Framework 5, Code-First.
I've two domain objects (or tables). 1st is User, and 2nd is UserProfile. One user can have only one profile, and one profile belongs to only one user. That is 1-1 relationship.
Here are the classes.... (I simplified the code to make it understandably, It is actually more complex)
User
public class User {
public virtual Int64 UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual String Username{ get; set; }
public virtual String Email { get; set; }
public virtual String Password { get; set; }
}
UserProfile
public class UserProfile {
public virtual Int64 UserId { get; set; }
public virtual User User { get; set; }
public virtual Int64 Reputation { get; set; }
public virtual String WebsiteUrl { get; set; }
}
Here are the Maps....
UserMap
public UserMap() {
this.Property(t => t.Email)
.IsRequired()
.HasMaxLength(100);
this.Property(t => t.Password)
.IsRequired()
.HasMaxLength(15);
this.Property(t => t.Username)
.IsRequired()
.HasMaxLength(15);
}
UserProfileMap
public UserProfileMap()
{
this.HasKey(t => t.UserId);
}
Here is the Context....
public class TcContext : DbContext {
static TcContext () {
Database.SetInitializer(new TcContextInitializer());
}
public DbSet<User> Users { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new UserProfileMap());
}
}
And here is my error message....
Unable to determine the principal end of an association between the types 'Tc.Domain.UserProfile' and 'Tc.Domain.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
I think in this way EF should determine the relationship automatically. But it gives me the above error message. I've researched this problem for a while but can't find a good illustration of the problem in my case.
Where is my mistake? Or, should I define some sort of additional relations in maps?
I had to modify the UserMap class as follows
public UserMap() {
this.Property(t => t.Email)
.IsRequired()
.HasMaxLength(100);
this.Property(t => t.Password)
.IsRequired()
.HasMaxLength(15);
this.Property(t => t.Username)
.IsRequired()
.HasMaxLength(15);
this.HasOptional(t => t.UserProfile)
.WithRequired(t => t.User);
}
It essentially says:
"User has an optional entity UserProfile which in turn has a required User entity"
The definition of the key in UserProfile is a must here.
Just looked at it again, do you need to add HasKey to UserMap so it knows which one is the key otherwise you could do the following :-
Are you able to change UserProfile to inherit from User and then add this to your OnModelCreating method
modelBuilder.Entity().ToTable("UserProfile");
this will create your one to one relationship on the database. I had to do this with my current model to get one to one otherwise if you do not specify the ToTable part it will lump them into one table with a Discriminator column
cheers Mark