Here I'm writing logic in class file and implementing in a controller. When I'm trying to implement the code in the controller it's throwing an error as "cannot assign void to an implicitly-typed local variable"
public void Getass()
{
var xx = from n in db.Accessors
join cn in db.Countrys on n.CountryID equals cn.CountryID
select new
{
n.Name,n.Id,n.CountryID,
cn.CountryName};
}
Dummy.cs
public JsonResult tt()
{
var sss= objrepo.Getass();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Getass should return the collection but it is an anonymous type. Either create it in the method making the call
public JsonResult tt()
{
var xx = from n in db.Accessors
join cn in db.Countrys on n.CountryID equals cn.CountryID
select new
{
n.Name,
n.Id,
n.CountryID,
cn.CountryName
};
return Json(xx, JsonRequestBehavior.AllowGet);
}
or create a class to hold the result
public class MyModel {
public string Name { get; set; }
public string Id { get; set; }
public string CountryID { get; set; }
public string CountryName { get; set; }
}
public IList<MyModel> GetAccessors()
{
var xx = from n in db.Accessors
join cn in db.Countrys on n.CountryID equals cn.CountryID
select new MyModel
{
Name = n.Name,
Id = n.Id,
CountryID = n.CountryID,
CountryName = cn.CountryName
};
return xx.ToList();
}
public JsonResult tt()
{
var sss= objrepo.GetAccessors();
return Json(sss, JsonRequestBehavior.AllowGet);
}
You'll need to create a concrete type to return that from your method. void means the method doesn't return anything, and you can't use var as a return type.
So your choices are:
Create a concrete type and have your query create objects of that type (and change your return type to IEnumerable<{type}> or similar
Put the query from Getass inside the tt method so you can use an anonymous type.
you can't return a void type and expecting a result that you can assign to a variable
more you are creating an anonymous type by doing this
select new {
n.Name,n.Id,n.CountryID,
cn.CountryName};
if you want to return it oops,
you can't return an anonymous type because you haven't the name at compilation time. c# will assign an arbitrary name once compiled so you have to use object type
You can only return object, or container of objects, e.g. IEnumerable<object>, IList<object>, etc.
Related
I am new C# and EF and LINQ
I am trying to learning (much like a toddler) how to do this so apologies if this is obvious
I am getting a type conversion error when i create a LINQ query
namespace ABC.Pages
{
public partial class AOmMainComponent
{
[Inject]
MydbContext MydbContext { get; set; }
public IEnumerable<OMSite> OMSites()
{
var Sites = from s in MydbContext.TblOms select new {SiteId = s.OMID, SiteName = s.OMSite };
return (IEnumerable<OMSite>)Sites;
}
}
public class OMSite
{
public int SiteID { get; set; }
public string SiteName { get; set; }
}
}
I've tried:
return Sites;
and I've tried
return (IEnumerable<OMSite>)Sites;
but neither work.Please can someone advise what i'm doing wrong?
thanks
john
Change:
var Sites = from s in MydbContext.TblOms select new {SiteId = s.OMID, SiteName = s.OMSite };
To:
var Sites = from s in MydbContext.TblOms select new OMSite {SiteId = s.OMID, SiteName = s.OMSite };
Particulary select new { -> select new OMSite{. After that return Sites; should work.
Your current code creates IEnumerable of anonymous types which can not be cast to IEnumerable<OMSite> which your IEnumerable<OMSite> OMSites() method expects to be returned.
You need to create the specific object in your projection:
var Sites = from s in MydbContext.TblOms select new OMSite {SiteId = s.OMID, SiteName = s.OMSite };
Your method is expecting you return IEnumerable<OMSite> and your query is creating an IEnumerable of a Anonymous types
I am trying to get a result from LINQ query and pass it to different function to use there.
This is my first function that called from browser. Then, GetAddressByIncIDis called.
// GET: Hello/5
public void GetModel(int? incID)
{
var incAddress = GetAddressByIncID(incID);
var siteID = GetSiteIDbyAddress(incAddress);
LoadSite(siteID);
}
private ?returntype? GetAddressByIncID(int? incID)
{
var incAddress = (from address in db.Incs
where address.IncID == incID
select new
{
IncID = address.IncID,
Number = address.Number,
Direction = address.Direction,
StreetName = address.StreetName,
Zip = address.Zip,
City = city.CityDesc,
State = state.StateDesc
}).FirstOrDefault();
return incAddress;
}
At this point, I could get a query result that I wanted. I only needed one or null so I set FirstOrDefault().
Within this function, I am able to access values inside of incAddress, like incAddress.IncID, and I want to do this in other function when it passed to them. Because its type is Anonymous Type, I am not sure what return type should I use.
Once this is returned, I pass it to other function that called GetSiteIDbyAddress to find out SiteID. This result may be multiple.
private ?returntype? GetSiteIDbyAddress(string incAddress)
{
var searchaddress = (from address in db.Addresses
where PrimaryAddressNumber == incAddress.Number && Direction == incAddress.Direction && StreetName == incAddress.StreetName
select new
{
SiteID = address.SiteID
});
return searchaddress;
}
Would you please give me a suggestion on both first and second function's return type? I searched and tried (list, array, etc) but could not find a great solution for it.
EDIT:
With suggestions, I have edited my code to looks below. Now I am able to use values from IncAddress to pass to the other function. However, the other problem arise.
public class IncAddress
{
public int IncID { get; set; }
public string Number { get; set; }
.
.
}
public class IncSite
{
public int? SiteID { get; set; }
.
.
}
private IncAddress GetAddressByIncID(int incID)
{
var incAddress = (from address in db.Incs
where address.IncID == incID
select new IncAddress
{
IncID = address.IncID,
Number = address.Number,
Direction = address.Direction,
StreetName = address.StreetName,
Zip = address.Zip,
City = city.CityDesc,
State = state.StateDesc
}).FirstOrDefault();
return incAddress;
}
private IncSite GetSiteIDbyAddress(IncidentAddress incidentAddress)
{
var searchaddress = (from address in db.Addresses
where PrimaryAddressNumber == incAddress.Number
select new IncSite
{
SiteID = address.SiteID
});
return searchaddress;
}
On GetSiteIDbyAddress, I get an error says:
Cannot implicitly convert type 'System.Linq.IQueryable <
HelloWorld.Controllers.HelloController.IncSite > ' to
'HelloWorld.Controllers.HelloController.IncSite'. An explicit
conversion exists (are you missing a cast?)
I think it is because I did not put FirstOrDefault() because I expect multiple record will be found by this query. How can I complete this function to get a multiple results?
You can do this in two ways, either by creating a new class Let it be some Address with those selected values as fields and in this case return type will respect to Address(Address if you use FirstOrDefault, List if you use .ToList() and so on). Or you can specify the return type as dynamic in this case no other changes is needed. But I suggest you to create a Class if possible and avoid the usage of dynamic in this case, since
it is a lot slower and won't have the same compile time error checks
as a proper class
updates as per David's comment
Case 1 :
//definition should be something like this
public class Address
{
public string IncID { get; set; }
public string Number { get; set; }
public string Direction { get; set; }
public string StreetName { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string State { get; set; }
}
And the Method should be like this:
private Address GetAddressByIncID(int? incID)
{
var incAddress = (from address in db.Incs
where address.IncID == incID
select new Address
{
IncID = address.IncID,
Number = address.Number,
Direction = address.Direction,
StreetName = address.StreetName,
Zip = address.Zip,
City = city.CityDesc,
State = state.StateDesc
}).FirstOrDefault();
return incAddress;
}
Case 2
private dynamic GetAddressByIncID(int? incID)
{
var incAddress = // Query here
return incAddress;
}
I have 2 tables in the database :
Table: Order (item_id)
Table: Item ( item_id)
When I'm doing the inner join in entity framework, as you can see below, I need to return in one list the result to manipulate this. Usually when I do the select in one single table , I return a LIST from the entity with the tables name, but I dont know how can I return a LIST when I have 2 or more entity , I mean, using inner join, I would like to return a List that I can manipulate in other class. When I use for only one entity, it is perfect and easy.
public List<????????> getTransdataByStatus(string status)
{
contenxt = new Finance_ManagementEntity();
var _result = (from a in contenxt.Orders
join b in contenxt.Items on a.item_id equals b.item_id
select new
{
a.order_numer,
a.total,
b.item_code,
b.item_qty
});
return _result;
}
I don't know how to return it !! I tried to use the .TOLIST(), but still coming "anonymous".
Thank you
First you need to create a custom type like
public class OrderItems
{
public int Order_numer { get; set; }
public int Total { get; set; }
public string Item_code { get; set; }
public int Item_qty { get; set; }
}
After then modify your function like
public List<OrderItems> getTransdataByStatus(string status)
{
contenxt = new Finance_ManagementEntity();
var _result = (from a in contenxt.Orders
join b in contenxt.Items on a.item_id equals b.item_id
select new OrderItems()
{
Order_numer= a.order_numer,
Total= a.total,
Item_code=b.item_code,
Item_qty=b.item_qty
}).ToList();
return _result;
}
I hope it will work for you.
You can create a compound model that has a property representing each entity.
public class CompoundModel
{
public Entities.Order { get; set; }
public Entities.Item { get; set; }
}
public List<CompoundModel> getTransdataByStatus(string status)
{
contenxt = new Finance_ManagementEntity();
var _result = (from a in contenxt.Orders
join b in contenxt.Items on a.item_id equals b.item_id
select new CompoundModel
{
Order = a
Item = b
});
return _result;
}
Alternatively, if you want to flatten your structure, you can create a class that only has four properties.
public class CompoundModel
{
public string OrderNumber { get; set; }
public int Total { get; set; }
public string ItemCode { get; set; }
public int ItemQuantity { get; set }
}
public List<CompoundModel> getTransdataByStatus(string status)
{
contenxt = new Finance_ManagementEntity();
var _result = (from a in contenxt.Orders
join b in contenxt.Items on a.item_id equals b.item_id
select new CompoundModel
{
OrderNumber = a.order_number,
Total = a.total,
ItemCode = b.item_code,
ItemQuantity = b.item_qty
});
return _result;
}
The problem with your code is this part:
select new // This will create an anonymous type
{
a.order_numer,
a.total,
b.item_code,
b.item_qty
}
As the select generates an anonymous type you will get a list of theses anonymous types as a result of the query. In order to get a list typed results, you need to specify the type in the select-clause:
select new TypeYouWantToReturn() // This will create an real type
{
PropA = a.order_numer, // You also need to specify the properties
PropB = a.total, // of the class that you want to assign
PropC = b.item_code, // the resulting values of the query.
PropD = b.item_qty
}
Now the result of the query will return a list of real types. You need to finally call .ToList() so you get a list instead of the IEnumerable that the select statement will return.
I am working with a action method in which I add a linq query with joins. Now I want to add view for this action method. But the problem is this the linq query is getting data from two entity models and I want to select strongly type view then which class I have to add for this. Here is the Action Method
public ActionResult Marks(int id)
{
var marksjoin = (from a in db.TbStudent
join b in db.TbMarks on a.StudentId equals b.StudentId
select new
{
a.StudentName,
b.StudentId,
b.Hindi,
b.English,
b.SocialStudy,
b.Science,
b.Maths,
b.Total
}).ToList();
// var marks = db.TbMarks.Where(m => m.StudentId == id).SingleOrDefault();
if (marksjoin == null)
{
return RedirectToAction("PostMarks");
}
else
{
return View(marksjoin);
}
Now I am getting the data from two entity models and how can I create a strongly type view for this ?
You need to create a new Type (resulting) and then dump your LINQ output into that Type:-
public class NewType
{
public List<Item> Items1{ get; set; }
public List<Item> Items2{ get; set; }
public string Items3{ get; set; }
............and so on
}
Then pass this 'NewType' as strong type to your view.
Query projection explained
var marksjoin = (from a in db.TbStudent
join b in db.TbMarks on a.StudentId equals b.StudentId
select new StudentType
{
StudentName = b.StudentName,
StudentId = b.StudentId,
// etc
}).ToList();
public class StudentType {
public string StudentName { get; set; }
public int StudentId { get; set; }
// etc...
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return anonymous type from LINQ query?
I use this Method:
public static ... GetList()
{
Entity conn = new Entity();
var lst = (from PS in conn.PurchaserSpecials
select new
{
PS.PurchaserID,
PS.PurchaserSerial,
PS.Purchaser.Address,
PS.Purchaser.Fax,
PS.Purchaser.NumberEconomic
}).ToList();
return lst;
}
can not use var for output Type. Please help me...
what is output the method?
It's a list of the anonymous type you created.
If you want to return a type that you would know, create a new class that has the fields you are selecting (I am guessing types below):
public class Specials
{
public int PurchaserID { get; set; }
public int PurchaserSerial { get; set; }
public string Address { get; set; }
public int Fax { get; set; }
public int NumberEconomic { get; set; }
}
public static List<Specials> GetList()
{
Entity conn = new Entity();
var lst = (from PS in conn.PurchaserSpecials
select new Specials
{
PurchaserID = PS.PurchaserID,
PurchaserSerial = PS.PurchaserSerial,
Address = PS.Purchaser.Address,
Fax = PS.Purchaser.Fax,
NumberEconomic = PS.Purchaser.NumberEconomic
}).ToList();
return lst;
}
You LINQ query generates an anonymous type, and as such can't be used as a return type of the method, and the calling method will not know anything about the return type.
A way around this is to make use of the dynamic keyword and dynamic types.
The return type of you method can be like this
public dynamic GetList() {
return ...;
The output of the query is an anonymous type which you can not return back as a parameter. To be simple, better you create a class something like : 'PurchaseDetail' with all those properties and return the code like :
public static List<PurchaseDetail> GetList()
{
Entity conn = new Entity();
var lst = (from PS in conn.PurchaserSpecials
select new PurchaseDetail
{
PurchaserID= PS.PurchaserID,
PurchaserSerial=PS.PurchaserSerial,
Address=PS.Purchaser.Address,
Fax=PS.Purchaser.Fax,
NumberEconomic =PS.Purchaser.NumberEconomic
}).ToList();
return lst;
}
The Return Type would be the List of type Products
public static List<Products> GetList()
{
Entity conn = new Entity();
var lst = (from PS in conn.PurchaserSpecials
select new
{
PS.PurchaserID,
PS.PurchaserSerial,
PS.Purchaser.Address,
PS.Purchaser.Fax,
PS.Purchaser.NumberEconomic
}).ToList();
return lst;
}
public class Products
{
//Properties you are using in the query.
}