【问题标题】:Get EntitySetName from EntityName in WCF Data Services从 WCF 数据服务中的 EntityName 获取 EntitySetName
【发布时间】:2010-09-21 17:09:31
【问题描述】:

我有一个名为 Client 的 EnityName,我需要它的集合名称 Clients,它必须是通用的,以便我可以从 EntityName 获取任何实体的 EntitySetName。它在 svc 文件中公开,但似乎不在服务代理类中。如果我能做到这一点,那么我可以有一个像这样的通用方法。

public void Add<T>(IEnumerable<T> entitySet)
{
    var myService = GetServiceContext();

    foreach (var entity in entitySet)
    {
        myService.AddObject(entity.GetType().Name -- NEEDS TO BE ENTITY SET NAME, entity);
    }

    myService.SaveChanges(SaveChangesOptions.Batch);

}

【问题讨论】:

    标签: c# wcf service


    【解决方案1】:

    我是这样实现的:

        private static string ResolveEntitySet(Type type)
        {
            var entitySetAttribute =
                (EntitySetAttribute) type.GetCustomAttributes(typeof (EntitySetAttribute), true).FirstOrDefault();
    
            if (entitySetAttribute != null)
            {
                return entitySetAttribute.EntitySet;
            }
    
            return null;
        }
    

    一个调用它的简单示例(与您的类似,但只有一个添加):

        public void Add<T>(T entity)
        {
            _entities.AddObject(ResolveEntitySet(entity.GetType()), entity);
        }
    

    这里是我的“帐户”实体在代理类中的外观峰值(在 .NET 4 中自动生成 - 我不必添加它,但看起来旧版本可能???)

    [System.Data.Services.Common.EntitySetAttribute("Accounts")]
    [System.Data.Services.Common.DataServiceKeyAttribute("Id")]
    public partial class Account : System.ComponentModel.INotifyPropertyChanged
    {
    

    【讨论】:

    • 嗨,我试过了,但客户端代理类上不存在 EntitySetAttribute。我确保为服务中的每个实体添加了 EntitySetAttribute。你是否必须做任何特定的事情才能让它与客户一起工作?另外,您使用的是哪个版本的 WCF 数据服务?
    • 我在 .Net Framework 4 上。我不需要对代理类做任何事情,因为 EntitySetAttribute 已经在那里了。很高兴这有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多