【发布时间】:2019-12-18 19:31:55
【问题描述】:
我正在学习 WCF 数据服务(5.6.4 版)。我找到了一个非常基本的例子。
CodeFirstSampleService.svc.cs 的代码:
public class CodeFirstSampleService : EntityFrameworkDataService<BlogContext>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
AddDataToBlogContext(new BlogContext());
}
private static void AddDataToBlogContext(BlogContext dataSource)
{
var b1 = new Blog() { BlogId = 1, BlogName = "SampleBlog" };
dataSource.Blogs.Add(b1);
dataSource.Posts.Add(new Post()
{
Blog = b1,
BlogId = b1.BlogId,
PostId = 1,
PostName = "Using EntityFrameworkProvider"
});
dataSource.SaveChanges();
}
[WebGet]
public string GetFirstPostName()
{
var context = new BlogContext();
return context.Posts.Select(x => x.PostName).FirstOrDefault();
}
}
DataModel.cs 的代码
public class Blog
{
public int BlogId { get; set; }
public string BlogName { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string PostName { get; set; }
//public ColorEnum Color { get; set; }
//public PostContent Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
效果很好。如果我开始调试(在浏览器中):
现在假设我在 Post 实体中也有一个枚举。
public class Post
{
public int PostId { get; set; }
public string PostName { get; set; }
public ColorEnum Color { get; set; } // <---- added ENUM here
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public enum ColorEnum
{
Red,
Green,
Blue
}
在运行时,启动服务时出现错误:“Post”类型上的“Color”属性属于“ColorEnum”类型,它不是受支持的原始类型。
我知道:WCF 数据服务不支持枚举。
一些解决方法是可能的:
例如在枚举属性上使用
[NotMapped]属性。但在我的情况下,我不能那样做,因为我已经在生产中使用 EF Code First 的解决方案,因为几年来有一些枚举并且我需要它,我不能简单地用实体上的 [NotMapped] 属性忽略它。-
我尝试添加
[DataMember]和[DataContract]属性但它不起作用:仍然收到有关枚举的错误消息。[DataContract] public class Post { [DataMember] public int PostId { get; set; } [DataMember] public string PostName { get; set; } public ColorEnum Color { get; set; } [DataMember] public int BlogId { get; set; } public virtual Blog Blog { get; set; } }
还有哪些其他选择?
请注意,我在我的上下文中有(假设是)20 个实体,但只需要其中 2 个就可以在我的 WCF 数据服务中使用。此外,只需要这 2 个实体处于“只读”模式(无需创建、更新等)。
如何使我的实体与枚举保持可用于应用程序的其余部分,但防止枚举属性在我的 WCF 数据服务中出现错误?
还请注意,我已经搜索了有关此主题的其他 SO 问题,但没有找到任何解决方案允许我在现有实体上保留枚举。
【问题讨论】:
标签: c# wcf wcf-data-services