Garry
Garry

Reputation: 174

EF 5 Inheritance Query Issue

I'm currently experiencing an issue with Entity Framework 5 not returning a record that exists when that entity is derived from an entity that has the property I'm querying against.

These are my entities:

public class Person
{
    [Key]
    public int Id { get; set; }

    public string Email { get; set; }
}

public class User : Person
{
    public  DateTime LastLoginDate { get; set; }    
}

My Data Context:

public class DataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().Map(m => { m.ToTable("User"); });

        modelBuilder.Entity<Person>()
                    .Property(x => x.Id)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

Repository:

public class UserRepository
{
    private readonly DataContext _dataContext;

    public UserRepository(DataContext dataContext)
    {
        _dataContext = dataContext;
    }

    public User GetByEmailAddress(string emailAddress)
    {
        if (string.IsNullOrEmpty(emailAddress))
            throw new ArgumentException("The emailAddress parameter cannot be null or empty.", "emailAddress");

        //This query works
        var working = _dataContext.Persons
            .FirstOrDefault(x => x.Email.Equals(emailAddress, StringComparison.CurrentCultureIgnoreCase));

        //Where as this returns null
        var query = _dataContext.Users
                .FirstOrDefault(x => x.Email.Equals(emailAddress, StringComparison.CurrentCultureIgnoreCase));

        return query;
    }
}

If I attempt to query for a Person by email address I get the record I'm looking for; however, if I query for a User by email address I get a null result.

Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 50

Answers (1)

Rick Dailey
Rick Dailey

Reputation: 130

How was the person you are looking for added? Were they added to the Persons collection or the Users collection when saved? Were they of type User or Person? What are the contents of the two tables (User and Person in your database).

I have duplicated the code above, but when I added the test user I added like:

_dataContext.Users.Add(new User { Email = emailAddress, LastLoginDate = DateTime.Now });
_dataContext.SaveChanges();

And both queries work fine (they return that user).

And even if I add them as a User type but to the Person collection, still both queries come back. The only time it doesn't work is if I add a Person type to the Person collection, then I get the results you outline above.

I would recommend marking the Person class "abstract" so that future developers are not tempted to create instances of that type.

Upvotes: 1

Related Questions