Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<FirstApp.Model.TeamDetails> - c#

I am getting this error
Cannot implicitly convert type
System.Collections.Generic.List<AnonymousType#1> to
System.Collections.Generic.List<FirstApp.Model.TeamDetails>
What's wrong with my code?
Here is my code
TeamDetails Class
public class TeamDetails
{
[Key]
public int TeamId { get; set; }
public string TeamName { get; set; }
public string Description { get; set; }
public int? UserCount { get; set; }
}
ViewModel
public class ViewTeamList
{
public List<TeamDetails> TeamNext { get; set; }
}
Controller
public ActionResult Next(int dataid)
{
ViewTeamList viewTeamList = new ViewTeamList();
var a = from t in tDbContext.Teams
join u in tDbContext.Users on t.TeamId equals u.TeamId into g
where t.Deleted != true
select new { TeamId= t.TeamId,TeamName = t.TeamName, Description = t.Description, UserId = g.Count() };
var next = a.OrderBy(t1 => t1.TeamId).Where(t1 => t1.TeamId > dataid).FirstOrDefault();
viewTeamList.TeamNext = a.ToList();
return PartialView("_ViewTeamDetails", viewTeamList);
}
I'm not able to assign this value to
viewTeamList.TeamNext = a....;

This constructs an anonymous type instead of TeamDetails
select new { TeamId= t.TeamId,TeamName = t.TeamName, Description = t.Description, UserId = g.Count() }
You should change it to below
select new TeamDetails { TeamId = t.TeamId, TeamName = t.TeamName, Description = t.Description, UserCount = g.Count() }
so a.ToList() would be a List<FirstApp.Model.TeamDetails>

Related

Filter data from 2 lists with diferent models C#

I have this models
public class RoutingAttributeModel
{
public int Bus_No { get; set; }
public int Attribute_No { get; set; }
public string Attribute_Name { get; set; }
public string Status { get; set; }
public string Notes { get; set; }
}
public class AgentRoutingAttributeModel
{
public int Agent_No { get; set; }
public int Bus_No { get; set; }
public int Attribute_No { get; set; }
public string Attribute_Name { get; set; }
public string Status { get; set; }
}
List<RoutingAttributeModel> lstComplete = new List<RoutingAttributeModel>();
List<AgentRoutingAttributeModel> lstAssigned = new List<AgentRoutingAttributeModel>();
Filled this with some data
Is it possible to filter with Linq? I want to save in a new list the diferent content between lstComplete and lstAssigned
I was trying to join both lists but got stuck there
var results1 = from cl in lstComplete
join al in lstAssigned
on cl.Attribute_No equals al.Attribute_No
select cl;
you can use linq
as my understanding, you try to find linked by attribute_No records and have a list of not matching properties?
lstComplete.Add(new RoutingAttributeModel(){
Attribute_Name = "aaa",
Attribute_No = 1,
Bus_No = 1,
Notes = "",
Status = "status"
});
lstAssigned.Add(new AgentRoutingAttributeModel()
{
Attribute_No = 1,
Agent_No = 10,
Bus_No = 1,
Attribute_Name = "bbb",
Status = "status2"
});
var lst = lstComplete
.Join(lstAssigned,
complete => complete.Attribute_No,
assigned => assigned.Attribute_No,
(complete, assigned) => new { lstComplete = complete, lstAssigned = assigned })
.Select(s => new { s.lstComplete, s.lstAssigned})
.Where(w=>
w.lstAssigned.Attribute_Name != w.lstComplete.Attribute_Name
|| w.lstAssigned.Bus_No != w.lstComplete.Bus_No
)
.ToList()
.Dump();
so result would be
You could try the following query
var filteredList = lstComplete
.Where(x => !lstAssigned.Any(y => y.Attribute_No == x.Attribute_No));

Add values to a list inside a list Linq

I am having a class like this.
public class CameraModel
{
public int JobId { get; set; }
public int ViewId { get; set; }
public Guid ViewGuid { get; set; }
public string Name { get; set; }
public int ViewNum { get; set; }
public int LayoutID { get; set; }
public List<CameraViewItemModel> CameraViewItems { get; set; }
}
The CameraViewItemModel class is like this:
public class CameraViewItemModel
{
public int JobID { get; set; }
public Guid ViewGuid { get; set; }
public int ViewID { get; set; }
public int CamNum { get; set; }
public Guid ChannelGuid { get; set; }
public string Name { get; set; }
public ActionType Action { get; set; }
}
Now, I am assigning the list of CameraViewItemModel like this:
// get all the cameramodel's
cameraModels = _unitOfWork.Context.CameraViews.Where(m => m.JobId == siteId)
.Select(m => new CameraModel
{
JobId = m.JobId,
ViewId = m.ViewId,
ViewGuid = m.ViewGuid,
Name = m.Name,
ViewNum = m.ViewNum,
LayoutID = m.LayoutId
}).ToList();
// get all the cameraviewitemmodels
cameraViewItemModels =
(from cameraView in _unitOfWork.Repository<CameraViews>().Get(x => x.JobId == siteId).Result
join cameraViewItem in _unitOfWork.Repository<CameraViewItems>().Get(x => x.JobId == siteId)
.Result on cameraView.ViewId equals cameraViewItem.ViewId into CameraViewItemResults
from cameraViewItemResult in CameraViewItemResults.DefaultIfEmpty()
join cameraChannel in _unitOfWork.Repository<CameraChannels>().Get(x => x.JobId == siteId)
.Result on (cameraViewItemResult == null ? new Guid() : cameraViewItemResult.ChannelGuid) equals cameraChannel.ChannelGuid into CameraChannelResults
from cameraChannelResult in CameraChannelResults.DefaultIfEmpty()
select new CameraViewItemModel
{
JobID = cameraView.JobId,
ViewID = cameraView.ViewId,
ViewGuid = cameraView.ViewGuid,
CamNum = cameraViewItemResult.CamNum,
ChannelGuid = cameraChannelResult.ChannelGuid,
Name = cameraChannelResult.Name
}).ToList();
// then do a 'join' on JobId, ViewId and ViewGuid and assign the list of cameraviewitemmodels to cameraModels.
foreach (var cameraModel in cameraModels)
{
cameraModel.CameraViewItems = (from cameraViewItem in cameraViewItemModels
where cameraModel.JobId == cameraViewItem.JobID
&& cameraModel.ViewId == cameraViewItem.ViewID
&& cameraModel.ViewGuid == cameraViewItem.ViewGuid
select cameraViewItem).ToList();
}
return cameraModels;
There are three tables in database:
CameraViews, CameraViewItems, CameraChannels.
CameraViews is the main table. It is left joined with CameraViewItems and CameraChannels to get the desired result. There may not be any data in CameraViewItems and CameraChannels for a corresponding CameraView.
Is it possible to assign the list of CameraViewItemModels to CameraModels in a single linq statement.
Here is a simple way to add values to a sub list, dunno if this is what you mean. You can keep selecting sub lists if that is necessary.
var parent_lst = new List<List<string>>(); // Root/parent list that contains the other lists
var sub_lst = new List<string>(); // Sub list with values
var selected_parent_lst = parent_lst[0]; // Here I select sub list, in this case by list index
selected_parent_lst.Add("My new value"); // And here I add the new value

Join with inner list

I have this linq query:
var investorData = from investor in db.Investors
join investorLine in db.InvestorStatementLines
on investor.InvestorID equals investorLine.InvestorID
where investor.UserId == userId
select new InvestorViewModel()
{
InvestorId = investor.InvestorID,
InvestorName = investor.Name,
FundingDate = investor.FundingDate,
DueDate = investor.DueDate,
FundsCommitted = investor.FundsCommitted,
FundsInvested = investor.FundsInvested,
StatementLines =
db.InvestorStatementLines.Where(s => s.InvestorID == investor.InvestorID)
.Select(t => new InvestorStatementLineVM
{
Balance = t.Balance,
Credit = t.Credit,
Debit = t.Debit,
InvestorStatementLineDetails = t.Details,
Date = t.Date
}).ToList()
};
The viewmodel:
public class InvestorViewModel
{
public int InvestorId { get; set; }
public string InvestorName { get; set; }
public DateTime FundingDate { get; set; }
public DateTime? DueDate { get; set; }
public Decimal? FundsCommitted { get; set; }
public Decimal? FundsInvested { get; set; }
public List<InvestorStatementLineVM> StatementLines { get; set; }
}
What is happening is once I'm executing the query I'm getting 125 records, and that's the number of the StatementLines for that investor. So I'm getting 125 same records but I'm expecting one result which will have 125 statement lines in the inner list.
Is this query correct?
This is how you can do that with navigation properties
var investorData = from investor in db.Investors
where investor.UserId == userId
select new InvestorViewModel()
{
InvestorId = investor.InvestorID,
InvestorName = investor.Name,
FundingDate = investor.FundingDate,
DueDate = investor.DueDate,
FundsCommitted = investor.FundsCommitted,
FundsInvested = investor.FundsInvested,
StatementLines = investor.InvestorStatementLines
.Select(t => new InvestorStatementLineVM
{
Balance = t.Balance,
Credit = t.Credit,
Debit = t.Debit,
InvestorStatementLineDetails = t.Details,
Date = t.Date
}).ToList()
};
Use GroupJoin instead of Join: (_join x in y on x.a equals y.a
into z_)
var investorData = from investor in db.Investors
join investorLine in db.InvestorStatementLines
on investor.InvestorID equals investorLine.InvestorID
into investorLine
where investor.UserId == userId
select new InvestorViewModel()
{
InvestorId = investor.InvestorID,
InvestorName = investor.Name,
FundingDate = investor.FundingDate,
DueDate = investor.DueDate,
FundsCommitted = investor.FundsCommitted,
FundsInvested = investor.FundsInvested,
StatementLines = investorLine
.Select(t => new InvestorStatementLineVM
{
Balance = t.Balance,
Credit = t.Credit,
Debit = t.Debit,
InvestorStatementLineDetails = t.Details,
Date = t.Date
}).ToList()
};
Also instead of performing the sub-query just use the data from the join you just performed.
A better option, using entity framework, is using navigation properties and then you do not need to perform a join but you just have
InvestorStatementLines as a property of your investor.
To set the navigation properties:
public class InvestorViewModel
{
public int InvestorId { get; set; }
public string InvestorName { get; set; }
public DateTime FundingDate { get; set; }
public DateTime? DueDate { get; set; }
public Decimal? FundsCommitted { get; set; }
public Decimal? FundsInvested { get; set; }
public virtual ICollection<InvestorStatementLineVM> StatementLines { get; set; }
}
And the query will be as simple as:
var investorData = from investor in db.Investors
where investor.UserId == userId
select new InvestorViewModel()
{
InvestorId = investor.InvestorID,
....
StatementLines = investor.InvestorStatementLines.Select(....)
};

Dapper MultiMapping not working

I'm trying to create a List of object Work using Dapper to do the mapping.
This is the code:
public class Work
{
public int id { get; set; }
public int id_section { get; set; }
public decimal price { get; set; }
public Model id_model { get; set; }
public Type id_type { get; set; }
}
class Model
{
public int id_model { get; set; }
public string Name { get; set; }
}
class Type
{
public int id_type { get; set; }
public string Name { get; set; }
}
public List<Work> GetListOfWork(int idList)
{
using (DatabaseConnection db = new DatabaseConnection()) //return a connection to MySQL
{
var par = new {Id = idList};
const string query = "SELECT id,id_section,price,id_model,id_type FROM table WHERE id_section = #Id";
return db.con.Query<Work, Model, Type, Work>(query,
(w, m, t) =>
{
w.id_model = m;
w.id_type = t;
return w;
}, par, splitOn: "id_model,id_type").ToList();
}
}
It doesn't give me any error but id_model and id_type in my the returned List are always empty (The object are created but all the fields are empty or null), other fields are mapped correctly.
Any clue ?
You need to add yourself the joins in the query string
Probably it is something like this
var par = new {Id = idList};
const string query = #"SELECT w.id,w.id_section,w.price,
m.id_model, m.Name, t.id_type, t.Name
FROM work w INNER JOIN model m on w.id_model = m.id_model
INNER JOIN type t on w.id_type = t.id_type
WHERE w.id_section = #Id";
return db.con.Query<Work, Model, Type, Work>(query,
(w, m, t) =>
{
w.id_model = m;
w.id_type = t;
return w;
}, par, splitOn: "id_model,id_type").ToList();

How do I load these LINQ results into my ViewModel class?

I have a LINQ query which returns results that match up with my PictureGallery class. I need to load them into my ViewModel but im getting the following error:
Cannot implicitly convert type
'System.Linq.IQueryable' to
'System.Collections.Generic.IEnumerable'.
An explicit conversion exists (are you missing a cast?)
I'm rather new at C#. How do I cast "Results" into my "PictureGallery" viewmddel class?
Thanks in advance!
Controller:
//Test MediaID
var MediaID = 75;
//Query Results
var Results = from g in DB.Galleries
join m in DB.Media on g.GalleryID equals m.GalleryID
where g.GalleryID == GalleryID
orderby m.MediaDate descending, m.MediaID descending
select new { g.GalleryTitle, Media = m };
//Create my viewmodel
var Model = new GalleryViewModel
{
MediaID = MediaID,
PictureGallery = Results, //This line throws the error.
PictureCount = Results.Count()
};
ViewModels:
public class GalleryViewModel
{
public int? MediaID { get; set; }
public IEnumerable<PictureGallery> PictureGallery { get; set; }
public int PictureCount { get; set; }
}
public class PictureGallery
{
public int GalleryID { get; set; }
public string GalleryTitle { get; set; }
public int MediaID { get; set; }
public string MediaTitle { get; set; }
public string MediaDesc { get; set; }
public double Rating { get; set; }
public int Views { get; set; }
}
Rephrase your query as:
//Query Results
var Results = from g in DB.Galleries
join m in DB.Media on g.GalleryID equals m.GalleryID
where g.GalleryID == GalleryID
orderby m.MediaDate descending, m.MediaID descending
select new PictureGallery {
GalleryID = g.GalleryId,
GalleryTitle = g.GalleryTitle,
MediaID = m.MediaID,
MediaTitle = m.MediaTitle,
MediaDesc = m.MediaDesc,
Rating = m.Rating,
Views = m.Views} ;
You are trying to set an IEnumerable<PictureGallery> to an IQueryable<anonymous>. You need to transform to the correct type:
var Model = new GalleryViewModel
{
MediaID = MediaID,
PictureGallery = Results
.Select(r => new PictureGallery {
GalleryID = r.Media.GalleryID,
GalleryTitle = r.GalleryTitle,
MediaID = r.Media.MediaID,
... // and so on
}),
PictureCount = Results.Count()
};
Then You can write
var list = result.ToList();
Then pass it to view like this
return View(list);
You can accept it in your view like this
#model List
Where ViewModel is a simple class with properties to accept the resultant values after query execution.
You can check these attachments[Linq query,View Model,Viewenter image description here][1]

Categories