Does WCF Data Services support working with Entity Framework Code First (4.1)? It seems like it's having a hard time understanding what to do with DbSet
or DbContext
. I suppose this shouldn't be too surprising since EFCF was released after Data Services.
internal class Context:DbContext {
public Context(String nameOrConnectionString) : base(nameOrConnectionString) { }
public DbSet<AlertQueue> Alerts { get; set; }
}
public class EntitySet:Abstract.EntitySet {
public EntitySet(String nameOrConnectionString) {
var context = new Context(nameOrConnectionString);
this.AlertQueueRepository = new Concrete.AlertQueueRepository(new Repository<AlertQueue>(context, context.Alerts));
}
}
publ开发者_开发百科ic class AlertQueueRepository:EntityRepository<AlertQueue> {
public AlertQueueRepository(IEntityRepository<AlertQueue> entityRepository):base(entityRepository) { }
public IQueryable<AlertQueue> Pending {
get {
return (from alert in this.All
where alert.ReviewMoment == null
select alert);
}
}
}
EntityRepository
and IEntityRepository
provide generic methods for All
and other CRUD functions. This is the WCF Data Service that isn't working:
public class WcfDataService1:DataService<Domain.Concrete.AlertQueueRepository> {
public static void InitializeService(DataServiceConfiguration config) {
config.SetEntitySetAccessRule("All", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
You need to install Microsoft WCF Data Services 2011 CTP2.
Here is a good step by step article from the ADO.NET Team Blog: Using WCF Data Services with Entity Framework 4.1 and Code First
You will need to change the reference for “System.Data.Services” and “System.Data.Services.Client” to “Microsoft.Data.Services” and “Microsoft.Data.Services.Client” after installing the CTP and then you will have a new V3 protocol version (DataServiceProtocolVersion.V3)
Add a constructor like below to pass in a connection string or database name
public class HospitalContext : DbContext
{
public HospitalContext(string dbname) : base(dbname)
{
}
public DbSet<Patient> Patients { get; set; }
public DbSet<LabResult> LabResults { get; set; }
}
I just made this very simple test:
WCF Service:
public class WcfDataService : DataService<Context>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
Context:
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public Context()
{
this.Configuration.ProxyCreationEnabled = false;
}
}
[DataServiceKey("Id")]
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And it works but I'm afraid that it is read only. Here is a workaround to allow data modifications.
精彩评论