Daniel Arkley
Daniel Arkley

Reputation: 174

How can I handle derived types in Entity Framework 5 Code First and MVC?

I am working on a set of classes to represent an Asset Register in Entity Framework. For the sake of keeping the question simple, I have built three classes:

Asset

Contains fields which are applicable to all asset types, e.g. Asset ID, Serial Number, Purchase Date

Computer

Derives from Asset, adds on fields specific to Computer assets, e.g. MAC Address, Hostname

Monitor

Derives from asset, adds on fields specific to Monitor assets, e.g. Size


In pure C# I can instantiate these classes by calling, for example:

Computer DansComputer = new Computer(){ AssetID=12345, SerialNumber="12345", Hostname="DanComputer"};

The UI that I am using to capture new assets requires that the user enter base data about their new asset (from the Asset) class and then discriminate to say, for example, they are creating a Computer asset. I'm wondering if this is less than elegant... In it's current form, the pseudo-code to perform an Insert, regardless of the type of asset would be:

  1. Capture data about the Asset class
  2. Commit these data via EF to the Asset table
  3. Redirect to a view, dependent on the Asset type, to capture type specific data, e.g. new Computer view
  4. Retrieve the previously committed Asset, cast it to appropriate type (e.g. Computer) and project Computer-specific fields to the new object.
  5. Commit the Computer to the database.

I don't like the commit between views there.

Would a "valid" approach to be one whereby the user selects the type of Asset they wish to add (e.g. Computer, Printer) and then a view to create a new Computer/Printer is displayed? This solution sounds less than ideal to me, because:

  1. I would need to draw up an MVC view for each type of asset, which seems to violate the DRY principle to me...
  2. I would need to manually keep a list of all the possible asset types and display some kind of UI to allow the user to select which type they want to use.

I can't, however, think of any other way to make this UI.

Am I missing something really obvious here?

Upvotes: 2

Views: 259

Answers (1)

Piotr Stapp
Piotr Stapp

Reputation: 19828

I think the easiest way is to change your steps:

  1. Give user a choice: which asset is it
  2. Reditect to proper action for this asset
  3. Render view with common parts for Asset (using for example partial view) and specified for selected one
  4. Retrieve data and commit it to database.

Upvotes: 1

Related Questions