WCF数据服务和实体框架代码第一?

时间:2011-06-01 17:44:53

标签: entity-framework-4.1 wcf-data-services

WCF数据服务是否支持使用Entity Framework Code First(4.1)?看起来很难理解如何处理DbSetDbContext。我认为这不应该太令人惊讶,因为EFCF是在数据服务之后发布的。

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));
    }
}

public 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);
        }
    }
}

EntityRepositoryIEntityRepositoryAll和其他CRUD函数提供了通用方法。这是无效的WCF数据服务:

public class WcfDataService1:DataService<Domain.Concrete.AlertQueueRepository> {
    public static void InitializeService(DataServiceConfiguration config) {
        config.SetEntitySetAccessRule("All", EntitySetRights.AllRead);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }
}

2 个答案:

答案 0 :(得分:2)

我刚做了这个非常简单的测试:

WCF服务:

public class WcfDataService : DataService<Context>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }
}

上下文:

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; }
}

它有效,但我担心它是只读的。 Here is a workaround允许修改数据。

答案 1 :(得分:2)

您需要安装Microsoft WCF Data Services 2011 CTP2

以下是ADO.NET团队博客中的一篇很好的分步文章:Using WCF Data Services with Entity Framework 4.1 and Code First

您需要更改“System.Data.Services”和“System.Data.Services.Client”的引用 安装CTP后“Microsoft.Data.Services”和“Microsoft.Data.Services.Client”,然后你将有一个新的V3协议版本(DataServiceProtocolVersion.V3)

添加如下所示的构造函数以传入连接字符串或数据库名称

public class HospitalContext : DbContext
{
    public HospitalContext(string dbname) : base(dbname)
    {
    }

    public DbSet<Patient> Patients { get; set; }
    public DbSet<LabResult> LabResults { get; set; }
}