It’s possible I shouldn’t even be attempting this in the first place, but here’s what I have so far:
public List<int> AuthorIDs
{
get
{
var l = new List<int>();
using (var context = new GarbageEntities())
{
foreach (var author in context.Authors.Where(a => a.Books.Any(b => b.BookID == this.BookID)).ToList())
{
l.Add(author.AuthorID);
}
}
return l;
}
set; //compiler error
}
How would I leave the above setter without any sort of custom logic? In the olden days I think you would just use:
set { authorIDs = value; }
which doesn’t work now.
Is this whole idea just terrible to begin with?
Edit:
To answer some people’s questions: I’m attempting to combine MVC with Data Annotation validation, with default binding, with Entity Framework 4.0…and failing quite fantastically, I believe.
This answer goes a bit wider than simply getting rid of the setter on the property – combine it with the rest of the answers and comments, and take the bits that make sense. Hopefully the bit at the end will help too, maybe just not right now.
If you’re using this in a model for data binding purposes and thus want it exposed as a property, I would do something like this:
Make a service which you will call to populate your model:
In your controller:
I explicitly haven’t included how to instantiate the book service in the controller. My preference would be to inject it at runtime in a constructor, but this will require you to have a custom controller factory – one step at a time. You could just new it up in the default constructor:
In an ideal world though, I would do this:
However the default MVC controller factory expects controllers to have a default parameter, so doing it with constructor injection will take a bit more work.