EntityDataSource with Code-First Entity Framework 4.1

987 Views Asked by At

I am just starting out on Entity Framework 4.1 Code-First. I have created my classes and DbContext, and they work perfectly fine. Right now I want to bind my ListView to my Entities, with the help of an EntityDataSource, but unfortunately it does not recognise any available connection strings! I think the providerName must be System.Data.EntityClient for it to work, but I have no concrete entity model to reference to...

I have read that an ObjectContext can be "adapted" from the DbContext, which in turn can be used to create an ObjectDataSource. I want to use my DbContext to bind to my ListView, however. Is there any way I can do this?

1

There are 1 best solutions below

0
On

I have a hard time understanding your question... You want to specify the connection string when you instanciate your Context class, is that it?

You can create an overload of your constructor of your DbContext class, like

public MyContext(string connString) : base (connString)
   {
      Database.SetInitializer(...
      ...
   }

Then, in a Code-First approach, you don't really need the ObjectContext except for super-advanced scenarios, and databinding isn't one of them I guess. To get to bind to a collection in your Context class, just put a property for it in a ViewModel class designed for your screen, like

public class MyViewModel
{
   private MyContext _context;
   public ObservableCollection<MyObject> MyObjects { get; set; }

   public MyViewModel()
   {
      _context = new MyContext();
      MyObjects = new ObservableCollection<MyObject>(_context.MyObjects.ToList());
   }
}

Then you can bind your ListView against that property, given that it's referenced.

Hope it helps, otherwise please give more details.