Quantcast
Channel: Entity Framework
Viewing all articles
Browse latest Browse all 10318

Commented Issue: An exception when I handle inheritance with EF code first [1206]

$
0
0
When I handle inheritance with EF code first, I hit an exception. My code like this:
```
public abstract class ProjectOwner
{
[key]
public string Id { get; set; }
...
}

[Table("Organizations")]
public class Organization : ProjectOwner
{
...
}

[Table("Users")]
public class User : ProjectOwner
{
...
}

public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Organization> Organizations { get; set; }
}

public User FindUserById(userId)
{
var context = new Context();
return context.Users.Find(userId);
}
```
I found that, when I find an user with userId, it will find the userId in ProjectOwners table. So, it may find a ProjectOwner object whose id is the same as the userId. Then, it will try to convert the ProjectOwner object to UserObject to return. Due to the actual ProjectOwner object may be an Organization not an User, it will raise an exception:
>The specified cast from a materialized 'System.Data.Entity.DynamicProxies.Organization_0D12134520D0F1937F8CB863E385A76833296BFEB7AD53A881C510B5B2C68008' type to the 'User' type is not valid.

That's very strange, my code is context.Users.Find() not context.ProjectOwners.Find(), why not find in Users table only?

Comments: I'm not think this should be by design. If it is the by design and the reason is as you said, how do we explain the follow behavior? context.Users.FirstOrDefault(userId) For the same userId, FirstOrDefault() will return null but Find() will raise exception. If return null is "not very helpful because this would imply that a user entity with the key can be created and inserted, which is not ture.", why FirstOrDefault() will return null?

Viewing all articles
Browse latest Browse all 10318

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>