简体   繁体   中英

Get EntitySetName from EntityName in WCF Data Services

I have a EnityName called Client and I need it's collection name Clients, it has to be generic so that I can get the EntitySetName from EntityName for any entity. It's exposed in the svc file but doesn't seem to be in the service proxy class. If I can do this then I can have a generic method like.

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

}

Here's how I implemented it:

    private static string ResolveEntitySet(Type type)
    {
        var entitySetAttribute =
            (EntitySetAttribute) type.GetCustomAttributes(typeof (EntitySetAttribute), true).FirstOrDefault();

        if (entitySetAttribute != null)
        {
            return entitySetAttribute.EntitySet;
        }

        return null;
    }

An a quick example of calling it (similar to yours, but with a single add):

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

Here a peak at how my "Account" entity looks in my proxy class (auto generated in .NET 4 - I didn't have to add this, but it looks like older versions might???)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM