Return Anonymous Type Results

Return anonymous type results?

I tend to go for this pattern:

public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}

public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}

It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.

Return Anonymous Type from a function

This is a very popular question. In general you cannot return an anonymous type due to the requirement of strong typing. However there are a couple of workarounds.

  1. Create a simple type to represent the return value. (See here and here). Make it simple by generating from usage.
  2. Create a helper method to cast to the anonymous type using a sample instance for casting.

Returning anonymous type in C#

You can't.

You can only return object, or container of objects, e.g. IEnumerable<object>, IList<object>, etc.

How to return anonymous type from EF sql query

It appears that EF doesn't support returning any types other than ones that have EF mappings when using the ObjectContext.ExecuteStoreQuery() method.

I ended up using a SqlCommand object and datareader with an anonymous type.

Is there a way to return Anonymous Type from method?

Returning it as a System.Object is the only way to return an anonymous type from a method. Unfortunately there is no other way to do this since anonymous types were designed specifically to prevent their use in this way.

There are some tricks that you can do to in conjunction with returning an Object that allow you to get close. If you are interested in this workaround please read Can't return anonymous type from method? Really?.

Disclaimer: Even though the article I linked does show a workaround that doesn't mean it is a good idea to do it. I would strongly discourage you using this approach when creating a regular type would be safer and easier to understand.

Is it good practice to return anonymous type in respond to HTTP GET request?

You right, you will have the same resulting serialized object (xml, json), and you can use anonymous type. But you should keep in mind:

  1. When your explicitly define resulting class, your code will be
    cleaner
  2. For explicitly defined resulting class your may define some validation
    rules using attributes for serializer
  3. If you use documentation tools, for example swagger, you also may use attributes to provide additional documentation.

Api should not be ambiguous.
Everything depends on your preferences. If you want use anonymous type, you may.

Method that returns anonymous type C#

You shouldn't return an anonymous type. Instead you should create a regular named class and use that as return type.

Anonymous types are good when their scope is just inside the method itself. They have no use outside the method. How would you for example know the property names if their definition is not public? The only solution is to create a class.

If you still want to return an anonymous type, you should return object or dynamic, both I am not really happy about when using that as return type.


Regarding your update: you have to use the named types in the code initializing the instances too (probably LINQ). C# doesn't automatically convert anonymous types to named types.

How to return an anonymous type after joining two models

You can probably clean this is up some but to give you an idea of what you can do. Create a new class and name it something that's meaningful.. I just used MyModel

public class MyModel
{
public bool extra { get; set; }
public string label { get; set; }
public string techtype { get; set; }
public string status { get; set; }
public string customername { get; set; }
public string resourcename { get; set; }
public string sitename { get; set; }

public static List<MyModel> AutoComplete(string term, string SearchBy)
{
using (var repository = new MyDataContext())
{
if (SearchBy == "Tag")
{
var tech = repository.AllFindTechnolog(term.Trim()).ToList();
var resources = repository.GetResources(tech.Select(a => a.IT360ID.Value).ToArray(), false).ToList();
var query = from techItems in tech
join resourcesItems in resources
on techItems.IT360ID.Value equals resourcesItems.RESOURCEID // join based on db2ID
orderby techItems.PartialTag
select new MyModel { extra = true, label = techItems.Tag.ToString(), techtype = techItems.TechnologyType.Name, status = resourcesItems.ResourceState.DISPLAYSTATE, customername = resourcesItems.ResourceLocation.SiteDefinition.AccountDefinition.ORG_NAME.ToString(), resourcename = resourcesItems.RESOURCENAME.ToString(), sitename = resourcesItems.ResourceLocation.SiteDefinition.SDOrganization.NAME };

return query.ToList();
}
else
{
var activeResources = repository.FindActiveResourceByName(term.Trim(), true).ToList();//.OrderBy(p => p.RESOURCENAME).Select(a => new { label = a.RESOURCENAME }).ToList();
var resources = repository.GetResources(activeResources.Select(a => a.RESOURCEID).ToArray(), false).ToList();
var tech = repository.getTechnologiesByIT360ids(activeResources.Select(a => a.RESOURCEID).ToArray()).ToList();
var query = from techItems in tech
join resourcesItems in resources
on techItems.IT360ID.Value equals resourcesItems.RESOURCEID // join based on db2ID
orderby techItems.Tag
select new MyModel { extra = true, label = resourcesItems.RESOURCENAME.ToString(), techtype = techItems.TechnologyType.Name, status = resourcesItems.ResourceState.DISPLAYSTATE, customername = resourcesItems.ResourceLocation.SiteDefinition.AccountDefinition.ORG_NAME.ToString(), resourcename = techItems.Tag.ToString(), sitename = resourcesItems.ResourceLocation.SiteDefinition.SDOrganization.NAME };

return query.ToList();
}
}
}
}

now when you want to use this in your action result you can just call

public ActionResult AutoComplete(string term, string SearchBy)
{
return Json(MyModel.AutoComplete(term, SearchBy),JsonRequestBehavior.AllowGet);
}


Related Topics



Leave a reply



Submit