Question

I have a pair of simple classes generating a database in Code First in EF 4.1:

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
}

public class Purchase
{
    public int PurchaseId { get; set; }
    public int UserId { get; set; }
    public int? SalespersonUserId { get; set; }

    public User User { get; set; }
    public User SalespersonUser { get; set; }
}

public class NewItemsDataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Purchase> Purchases { get; set; }
}

In my program, I create and write some data to it.

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<NewItemsDataContext>(new DropCreateDatabaseIfModelChanges<NewItemsDataContext>());

        using (NewItemsDataContext sadc = new NewItemsDataContext())
        {
            sadc.Users.Add(new User());

            sadc.SaveChanges();
        }
        using (NewItemsDataContext sadc = new NewItemsDataContext())
        {
            sadc.Purchases.Add(new Purchase() { UserId = 1 });
            sadc.SaveChanges();
        }
        using (NewItemsDataContext sadc = new NewItemsDataContext())
        {
            var sql = sadc.Purchases.Include(p => p.User);
            foreach (Purchase purchase in sql)
                Console.WriteLine(purchase.User.UserId.ToString());
        }
    }
}

Note, when I read the Purchase records back, I get an exception of purchase.User being null -- that is, the .Include did not pull anything in for the User. Now, if I ignore the salespersonUser navigation property in my OnModelCreating (or just comment it out):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Purchase>().Ignore(p => p.SalespersonUser);

    base.OnModelCreating(modelBuilder);
}

The code works, and the User is loaded in the .Include.

When the SalespersonUser nav property is ignored, the created database looks as you would expect it. The Purchase table has a PurchaseId, UserId, and SalespersonId. But once you add the SalespersonUser nav property back in (stop ignoring it), you end up with two more keys in the table: User_UserId and SalespersonUser_UserId (as well as the original UserId and SalespersonUserId).

Also, the SQL generated definitely shows where the problem arises.

Without the nav property:

{SELECT 
[Extent1].[PurchaseId] AS [PurchaseId], 
[Extent1].[UserId] AS [UserId], 
[Extent1].[SalespersonUserId] AS [SalespersonUserId], 
[Extent2].[UserId] AS [UserId1], 
[Extent2].[UserName] AS [UserName]
FROM  [Purchases] AS [Extent1]
INNER JOIN [Users] AS [Extent2] ON [Extent1].[UserId] = [Extent2].[UserId]}

and with the nav property:

{SELECT 
[Extent1].[PurchaseId] AS [PurchaseId], 
[Extent1].[UserId] AS [UserId], 
[Extent1].[SalespersonUserId] AS [SalespersonUserId], 
[Extent2].[UserId] AS [UserId1], 
[Extent2].[UserName] AS [UserName], 
[Extent1].[SalespersonUser_UserId] AS [SalespersonUser_UserId]
FROM  [Purchases] AS [Extent1]
LEFT OUTER JOIN [Users] AS [Extent2] ON [Extent1].[User_UserId] = [Extent2].[UserId]}

Notice how it pulls the UserId, but joins with the User_UserId, and a left join, no less. The SalespersonUserId isn't even referenced in a join. Inside the database after writing the record, the UserId is set, but the User_UserID is null. Thus, nothing to join, and we get null for the Included User.

It would seem to me that this is a bug in EF, but it is possible there is a design reason for it. If so, can someone clear it up for me, and perhaps describe some fluent API that may work around it? I'm kind of partial to my nav properties.

Was it helpful?

Solution

EF is having problems w/ your navigation properties - thats why it's generating the extra FK's.

Try adding this fluent mapping, so you'r explicitly mapping the FK to nav property relationship:

        modelBuilder.Entity<Purchase>()
            .HasOptional(p => p.SalespersonUser)
            .WithMany()
            .HasForeignKey(p => p.SalespersonUserId);

        modelBuilder.Entity<Purchase>()
            .HasRequired(p => p.User)
            .WithMany()
            .HasForeignKey(p => p.UserId);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top