开发者

C# viewmodel: model --> Can't get typecasting working

开发者 https://www.devze.com 2023-02-14 06:53 出处:网络
I am creating a linq-to-sql model with EF, and have a class that works well, however, I want to be able to make additions to the class and not have them overwritten when I make changes with EF, so I b

I am creating a linq-to-sql model with EF, and have a class that works well, however, I want to be able to make additions to the class and not have them overwritten when I make changes with EF, so I believe I need to use a second layer of view class.

So, I have:

public partial class People: INotifyPropertyChanging, INotifyPropertyChanged {...} // created by EF

then want to do:

public partial class ViewPeople: People {
   public String someFunction() {...} // additional functionality
}

however, when I try to cast from People to ViewPeople using the code further below, I get an exception:

Unable to cast object of type 'Namespace.Models.People' to 'Namespace.Models.ViewPeople'

Code:

开发者_C百科
//select the person
NSDataContext dc = new NSDataContext(); // to get to the data context and models froM EF
var person = (from p in dc.Peoples where p.id == personID select p).First();

// pass model to view
return View((ViewPeople)person)

If I just pass through person, I get access to all the "People" properties and methods. When I modify the ViewPeople class, i get access to all properties and methods of the super "People" class when referencing 'this'.

Sure it's something simple, but I just can't figure it out!

Any assistance on the matter would be appreciated, as would an example to where someone has implemented viewmodels ontop of auto-generated EF models!

Thanks in advance, Andrew


If you get a People from EF, you cannot magically convert it to a ViewPeople.
You can only cast an object to ViewPeople if it actually is a ViewPeople.

Instead, you need to give ViewPeople a constructor that takes a People and copies over its properties.


When the entity framework returns objects from data it fetches from the database, it creates People, not ViewPeople. That explains why you cannot cast your objects. If you want to add functionality to your People class, you can add this in another file in the same assembly:

public partial class People
{
    public String someFunction() {...} // additional functionality
}

Another thing you can do is make the ViewPeople class take a People instance in its constructor, wrap the People instance's properties (yikes!) and change your query to be:

//select the person
NSDataContext dc = new NSDataContext(); // to get to the data context and models froM EF
ViewPeople person = (from p in dc.Peoples where p.id == personID select new ViewPeople(p)).First();

// pass model to view
return View(person)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号