I have some method with linq query. Logic is next, if I pass null for list of role ids, I want all roles to be included in process, but if it has value, I want only those with id in the list. I am receiving exeption.
public static List<NameEmail> GetNameEmailPairs(Guid guid, List<int> recipientRoles)
{
using (var tc = TransactionContext())
{
var dc = tc.DataContext;
var nameEmailPairs = (
from email in dc.Emails
join logon in dc.Logons on email.GUID equals logon.GUID
join eLogon in dc.ELogons on logon.UID equals eLogon.LogonGUID
join role in dc.Roles on entityLogon.PrimaryPermissionRoleID equals role.RoleID
where
(recipientRoles == null || recipientRoles.Contains(role.RoleID))
select new NameEmail
{
Email = email.EmailAddress,
FullName = GetName(logon.GUID)
}
)
.ToList();
return nameEmailPairs;
}
}
This part is breaking (recipientRoles == null || recipientRoles.Contains(role.RoleID)). Can you please help me with this, what should I do?
To make debugging easier, break your query up into pieces like this:
var nameEmailPairs = (
from email in dc.Emails
join logon in dc.Logons on email.GUID equals logon.GUID
join eLogon in dc.ELogons on logon.UID equals eLogon.LogonGUID
join role in dc.Roles on entityLogon.PrimaryPermissionRoleID equals role.RoleID
select new {email, role}
);
if(recipientRoles != null)
{
nameEmailPairs = nameEmailPairse.Where(
recipientRoles.Contains(p => p.role.RoleID)
);
}
var nameEmailPairs = (from p in nameEmailPairs
select new NameEmail
{
Email = email.EmailAddress,
FullName = GetName(logon.GUID)
}).ToList();
Related
So I have the list that I want to join against a table on the db.
I am getting the error Unable to create a constant value of type, what am I doing wrong?
List<info.user> studyAccessList = new List<info.User>();
using (var Db = new Entities())
{
//get users from USER table
var UserDbQry = (from data in Db.USER
where data.System == "something" & data.Active == true
select data);
//outer join
var joinQry =
from s1 in UserDbQry
join t2 in studyAccessList
on new
{
Study = s1.Study,
Email = s1.Email
}
equals new
{
Study = t2.Study,
Email = t2.Email
}
into rs
from r in rs.DefaultIfEmpty()
//where r == null
select s1;
foreach (var inactiveUser in joinQry)
{
//add tag for system.
//create xml
string xml = String.Format("<User><Study>{0}</Study><Email>{1}</Email><Active>false</Active></User>", inactiveUser.Study, inactiveUser.Email);
recordCount = recordCount + ProcessXml(wsu, xml, log.ErrorMsgPrefix);
}
}
I needed to change the first query to a list then the second query was able to pick it up.
//get users from USER table
var UserDbQry = (from data in Db.USER
where data.System == "something" & data.Active == true
select data).ToList;
//outer join
var joinQry =
from s1 in UserDbQry
join t2 in studyAccessList
on new
{
Study = s1.Study,
Email = s1.Email
}
equals new
{
Study = t2.Study,
Email = t2.Email
}
into rs
from r in rs.DefaultIfEmpty()
//where r == null
select s1;
I've had issues with my query that I was finally able to work through, but now duplicate date is formed even with Distinct(). I know these joins are messy, unfortunately it's what I have to do since the tables I'm working with have no relationships between them.
try
{
//work on query further , need to get client ID correctly
if (vehicleses.Count == 0)
return null;
string siteId = QueryExportSiteWithId(exportSiteId).SiteId;
// db.Database.Log = Console.Write;
var joinedInventorySettings = await (from id in db.Inventory_Descriptions
join iv in db.Inventory_Vehicles
on new {client = id.ClientID, id = id.InventoryID} equals new {client = iv.ClientID, id = iv.ID}
into descGroup
from m in descGroup.DefaultIfEmpty()
join se in db.Settings_Exports
on m.ClientID equals se.ClientID into settingGroup
from sg in settingGroup.DefaultIfEmpty()
join sl in db.Settings_Lots
on new {client = m.ClientID, id = m.LotID} equals new {client = sl.ClientID, id = sl.ID} into
lotsGroup
from lg in lotsGroup.DefaultIfEmpty()
join ses in db.Settings_ExportSites on new {client = m.ClientID, lotId = m.LotID, site = siteId}
equals new {client = ses.ClientID, lotId = ses.LotID, site = ses.Site} into exportGroup
from eg in exportGroup.DefaultIfEmpty()
join ifs in db.Inventory_Features
on new {client = m.ClientID, id = m.ID} equals new {client = ifs.ClientID, id = ifs.InventoryID}
into invFeatGroup
from ifg in invFeatGroup.DefaultIfEmpty()
join ip in db.Inventory_Photos
on m.ID equals ip.InventoryID into photo
from photos in photo.DefaultIfEmpty()
where m.Archived != "1"
&& m.Holding != "1"
&& m.Status == "A"
&& clientIdList.Contains(m.ClientID)
select new JoinedInventorySettings()
{
InventoryVehicles = m,
InventoryDescriptions = id,
SettingsExports = sg,
//InventoryPhotos = ,
SettingsLots = lg,
InventoryFeatures = ifg,
SettingsExportSites = eg
}).Distinct().ToListAsync();
if (joinedInventorySettings != null)
{
returnList.AddRange(joinedInventorySettings);
return returnList;
}
return null;
}
If anyone is curious, I was able to fix the issue by grouping items by two of the entity keys that I know will be in the dataset.
I'm trying to do a left join in an EF query. I'm getting the following error:
Error CS1941 The type of one of the expressions in the join clause is
incorrect. Type inference failed in the call to 'GroupJoin'
and here is the C# code:
var foo = from m in db.ClientMasters
join a in db.Orders on new { m.Id, Status = "N" } equals new { a.ClientID, a.Status } into a_join
from a in a_join.DefaultIfEmpty()
select new { m.ClientID, a.ID };
The column names have to match in the join; here is the corrected code:
var foo = from m in db.ClientMasters
join a in db.Orders on new { ClientID = m.Id, Status = "N" } equals new { a.ClientID, a.Status } into a_join
from a in a_join.DefaultIfEmpty()
select new { ClientID = m.Id, OrderId = a.Id };
I'm trying to convert a DateTime value to a string, but I'm getting this runtime error:
Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be
translated into a store expression.
This is the query I'm using:
using (var db = new DbContext())
{
var results = (from u in db.AspNetUserses
join upi in db.UserPersonalInfoes on u.Id equals upi.UserId into upis
from upi in upis.DefaultIfEmpty()
join up in db.UserPreferenceses on u.Id equals up.UserId into ups
from up in ups.DefaultIfEmpty()
join us in db.UserStatses on u.Id equals us.UserId into uss
from us in uss.DefaultIfEmpty()
select new
{
Username = u.UserName,
Telephone = (upi == null ? String.Empty : upi.Telephone),
ID = u.Id,
LastLogin = (us == null ? String.Empty : us.LastLoginDate)
}).ToList();
gvUsers.DataSource = results;
gvUsers.DataBind();
}
Any idea how can I fix this error?
Create a second list and do the transformation there.
using (var db = new DbContext())
{
var results = (from u in db.AspNetUserses
join upi in db.UserPersonalInfoes on u.Id equals upi.UserId into upis
from upi in upis.DefaultIfEmpty()
join up in db.UserPreferenceses on u.Id equals up.UserId into ups
from up in ups.DefaultIfEmpty()
join us in db.UserStatses on u.Id equals us.UserId into uss
from us in uss.DefaultIfEmpty()
select new
{
Username = u.UserName,
Telephone = (upi == null ? String.Empty : upi.Telephone),
ID = u.Id,
LastLogin = (us == null ? DateTime.MinValue : us.LastLoginDate)
}).ToList();
var list = (from r in results
select new {
Username = r.UserName,
Telephone = r.Telephone,
ID = r.ID
LastLogin = r.LastLogin == DateTime.MinValue ? "" : r.LastLogin.ToString()
}).ToList();
gvUsers.DataSource = list;
gvUsers.DataBind();
}
New to MVC, Checked lot of workarounds.. didn't help:
This code is written in model repository, which returns a list that I can return to View(Index)
IList<AccessArticles> publisherList = (from aa in db.AccessArticles
join u in db.Users on aa.UserId equals u.id
join a in db.Articles on aa.ArticleId equals a.id
where u.id == id
orderby a.title
select new
{
UserName = u.username,
ArticleTitle = a.title,
AccessArticlesId = aa.AccessArticlesId,
ArticleId = aa.ArticleId,
UserId = aa.UserId
})
.AsEnumerable()
.Select
(x=> new AccessArticles
{
AccessArticlesId = x.AccessArticlesId,
UserId = x.UserId,
UserName = x.UserName,
ArticleTitle = x.ArticleTitle
}).ToList();
Error that I get is Specified cast is not valid.
Please suggest a wayout or a better way to get the same effect.
Thanks
Code reference -
Interface :
List<AccessArticles> SearchByUserId(int UserId);
Repository :
public List<AccessArticles> SearchByUserId(int id)
{
var setArticles = (from aa in db.AccessArticles
join u in db.Users on aa.UserId equals u.id
join a in db.Articles on aa.ArticleId equals a.id
where u.id == id
orderby a.title
select new AccessArticles
{
UserName= u.username,
ArticleTitle = a.title,
AccessArticlesId= aa.AccessArticlesId,
ArticleId = aa.ArticleId,
UserId = aa.UserId
}).ToList();
return setArticles;
}
Controller
public ActionResult Index(int? id)
{
int UserId = 0;
if (id != null)
{
UserId = Convert.ToInt32(id);
}
IAccessArticlesRepository AccessRepository = new AccessArticlesRepository();
//int count = AccessRepository.SearchByUserId(UserId).Count();
List_AccessArticles = AccessRepository.SearchByUserId(UserId);
return View(List_AccessArticles);
}
Model
namespace theSiteCMS.Models
{
public partial class AccessArticles
{
public string ArticleTitle { get; set; }
public string UserName { get; set; }
}
}
I did some changes taking some reference:
----------
Repository
----------
public IQueryable<AccessArticles> SearchByUserId(int id)
{
var setArticles = (from aa in db.AccessArticles
join u in db.Users on aa.UserId equals u.id
join a in db.Articles on aa.ArticleId equals a.id
where u.id == id
orderby a.title
select new AccessArticles
{
UserName= u.username,
ArticleTitle = a.title,
AccessArticlesId= aa.AccessArticlesId,
ArticleId = aa.ArticleId,
UserId = aa.UserId
});
return setArticles;
}
--------------
Controller
--------------
public ActionResult Index(int? id)
{
int UserId = 0;
if (id != null)
{
UserId = Convert.ToInt32(id);
}
IAccessArticlesRepository AccessRepository = new AccessArticlesRepository();
var userwisearticles = AccessRepository.SearchByUserId(UserId);
return View(userwisearticles);
}
Error:
In Index.aspx page:
<% foreach (var item in Model) { %>
Highlight on 'Model' - Explicit construction of entity type 'theSiteCMS.Models.AccessArticles' in query is not allowed.
This returns a collection of Anonymous types with the properties described below. If you need to use an existing class, make sure it's not the one your EF is using to represent your entity unless it matches directly. If that's the case, then you should be able to to replace the select new below with select aa and have it return a list of the entity models that EF built for you.
var publisherList = (from aa in db.AccessArticles
join u in db.Users on aa.UserId equals u.Id
join a in db.Articles on aa.ArticleId equals a.Id
where u.Id == userId
orderby a.Title
select new
{
UserName = u.UserName,
ArticleTitle = a.Title,
AccessArticleId = aa.AccessArticlesId,
UserId = aa.UserId
}).ToList();
Edited to select the EF entity directly;
var publisherList = (from aa in db.AccessArticles
join u in db.Users on aa.UserId equals u.Id
join a in db.Articles on aa.ArticleId equals a.Id
where u.Id == userId
orderby a.Title
select aa).ToList();
That should trigger a compile error because your return type doesn't match. I'm guessing it has to be List<AccessArticle>