简体   繁体   中英

Cannot access entity having int key from base controller (Odata WebAPI)

I have a base controller, which has a Get method as follows:

[Enable query]   
public T Get([FromOdataURI]string key)  
{  
  entity=GetDbSet().Find(key);  
}  

I cannot modify the find method. Its a method derived from a metadata file.

The problem is that the Get method accepts key as string. Hence if an entity is accessed which has a string primary key,

for eg: http://hostname/service-name/employee ('3000200') (here '3000200' is of type nvarchar in database),

the base controller is called and the get method defined in the base controller compares the string primary key with the string value in database.

But on the other hand, if an entity which has an integer key is accessed,

For eg: http://hostname/service-name/product(2) (here 2 is of type integer in database),

the base controller is called and the Get method still takes the key as string and when the code compares string key value to integer key value in database, it throws back an error saying "the argument type Edm.String and Edm.Int are incompatible". I don't want to create a separate controller for entities that do not have primary key as string. How can I handle different key datatypes in Get method of the base controller?

Add a second type parameter to your base class that specifies the type of the key.

public class BaseController<TKey, TEntity> : ODataController
{
    public TEntity Get([FromODataUri] TKey key) 
    {
        return GetDbSet().Find(key);
    }
}

Of course, this approach requires that Find(TKey) is defined.

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