Vinicius Ottoni
Vinicius Ottoni

Reputation: 4677

Cast issue with EF

I have the following user class:

public class CustomUser : User, IUser<int> {...}
public interface IUser<TKey> {...}

The class User is a partial class generated from my edmx (database to model method).

I'm trying to add a new user to database, but I got the error: "Mapping and metadata information could not be found for EntityType "MyNamespace.CustomUser".

He the code to add new user:

public void CreateUser(CustomUser user)
{
    User newUser = (User)user;
    this.MyEntities.Users.Add(newUser); <-- Line that error blows
    this.MyEntities.SaveChanges();
}

Why after the cast, the newUser keeps as CustomUser?

Upvotes: 2

Views: 319

Answers (1)

JotaBe
JotaBe

Reputation: 39015

newUser is a variable of type User but it points to the original CustomUser in memory.

If you run newUser.GetType() you'll get CustomUser.

To aovid this problem you'd need to create a new object of type user, and copy all of its properties. You can use AutoMapper or ValueInjecter to make it automatically, or do it by hand.

Another solution woudl be to configure the CustomUserin your EF model, so that it works as expected. You didn't specify how you have defined the EF model.

Upvotes: 2

Related Questions