简体   繁体   中英

Pass a model as a function parameter

I found the below code in C#.

var results= context.Database.SqlQuery <Student> ("select * from students").ToList();

would give me a list of Students and

var results= context.Database.SqlQuery <Teacher> ("select * from teachers").ToList();

would give me a list of teachers. These seem very similar to me. What I want to do is make the above into a function that takes a model and a string so I can just pass something like

GetList(Model myModel, string sqlString)
{
    return context.Database.SqlQuery<myModel>(sqlString).ToList();
}

Is that possible somehow?

You're looking into using generics.

Your method would look something like this:

GetList<T>(string sqlString)
{
    return context.Database.SqlQuery<T>(sqlString).ToList();
}

and then you'd call it replacing the T with your type, so:

var list = GetList<MyModel>("select * from table");

read about generics here

If You want Your function to return List of Your model class, make Your function use generic type :

        List<T> GetList<T>(string sqlString)
        {
            return context.Database.SqlQuery<T>(sqlString).ToList();
        }

Usage is very simple:

List<YourModel> yourList = GetList<YourModel>(sqlString);

This function will return list of any type for You.

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