TomSelleck
TomSelleck

Reputation: 6968

Better practise to hide sensitive fields in EF model or create a new class?

I'm using code-first with entity framework for modeling and creating my db.

I'm just wondering - when I return objects to the user - I don't want to return data sensitive fields like id.

Should I add an atttibute like [DoNotReturn] combined with a filter to remove this fields when returning to the user, or should I just make a whole new class which doesn't contain these fields?

Example:

public class UserAccount
{
    //Option 1 - Hide fields
    [DoNotReturn]
    public int Id { get; set; }

    [Index(IsUnique = true)]
    [MaxLength(50)]
    public string Username { get; set; }

    public decimal Cash { get; set; }

    [DoNotReturn]
    public Account Account { get; set; } //Contains Email / Password

    //Option 2 - return a `safe` version
    public User UserAccountToFriendly() {
        return new FriendlyUser(this.Username, this.Cash);
    }
}

Upvotes: 1

Views: 349

Answers (2)

Serhii Kyslyi
Serhii Kyslyi

Reputation: 1823

Never use your database models as result for end-users and keep it separate from Presentation/Application layer.

There are so many problems that you will encounter:

  • disclosure of sensitive data (you've mentioned about);
  • performance issues and waste of RAM and CPU (for instance, you have Order entity with dozens of properties, it would be better to load only those properties that is required instead all);
  • problems with serialization (with enabled lazy-loading, for instance MVC could try to serialize whole object with navigation properties... );
  • etc...

I'd like to recommend the following:

  • return original database entity from Repository layer if necessary, but don't forget to cast it on Presentation layer to another completely brand new xxxModel, xxxViewModel, xxxResponse, etc;
  • return xxxView from Repository layer if you want to achieve best optimizations, but don't forget to cast it on Presentation layer to brand new object. (any changes on one layer shouldn't affect others, especially end-users);

Upvotes: 2

Atul Chaudhary
Atul Chaudhary

Reputation: 3736

Keep your database model separate from your view model that's the approach I have taken and doing it for a long time. it will give you a good separation. Once you start dealing with ViewModel then you can use a library like Automapper or custom mapping classes to convert ViewModel to database model or vice-versa. I hope it helps

Upvotes: 3

Related Questions