MY SQl output
MY Output View Both are Different
The same query when fire in MS server Sql is proper value .
Row Count is same but only First row is repeated in LINQ ....
no error , no idea !
Table("SalarySlip")]
public class Document
{
[Key]
public string EmployeeID { get; set; }
public string Basic { get; set; }
public string Bonus { get; set; }
public string Flexi { get; set; }
public string HRA { get; set; }
public string Month { get; set; }
public string NetPay { get; set; }
public string OtherDeduction { get; set; }
public string PF { get; set; }
public string Special { get; set; }
public string TDS { get; set; }
public string TotalDeduction { get; set; }
public string TotalEarning { get; set; }
public string Year { get; set; }
}
public ActionResult EmpSalaryHistory(string EmployeeID )
{
DatabaseContext _context = new DatabaseContext();
var Userdata = _context.SalarySlip.Where(x => x.EmployeeID == EmployeeID).OrderByDescending(x => x.Month).ToList();
if (Userdata.Count != 0)
{
TempData["data"] = EmployeeID;
return View(Userdata);
}
else
{
TempData["data"] = EmployeeID;
//return View();
return RedirectToAction("Demo");
}
}
I want to send a collection of two different Collections as a Json but in a sorted format. I am not able to do it with Linq. Need little help.And also is there any better way. Thank you!
Here is my action.
public ActionResult GetAllJobPosts()
{
var Institutes = new List<Institute>()
{
new Institute(){InstituteId="ins1",InstituteName="name1",Location="Mumbai"},
new Institute(){InstituteId="ins2",InstituteName="name2",Location="Navi Mumbai"},
new Institute(){InstituteId="ins3",InstituteName="name3",Location="Thiruvananthpuram"}
};
var Companys = new List<Company>()
{
new Company(){CompanyId="com1",CompanyName="comName1",Location="Mumbai"},
new Company(){CompanyId="com2",CompanyName="comName2",Location="Navi Mumbai"},
new Company(){CompanyId="com3",CompanyName="comName3",Location="Mumbai"}
};
var Organizations = new List<Organization>()
{
new Organization(){OrganizationId="org1",OrganizationName="orgName1",Location="Navi Mumbai"},
new Organization(){OrganizationId="org2",OrganizationName="orgName2",Location="Navi Mumbai"},
new Organization(){OrganizationId="org3",OrganizationName="orgName3",Location="Mumbai"},
};
var CompanyJobPosts = new List<CompanyJobPost>()
{
new CompanyJobPost(){CompanyId="com1",CompanyJobPostId="com1jp1",CreatedOn=System.DateTime.Now.AddDays(-2),JobDiscription="Tester",KeySkils="Sylanium"},
new CompanyJobPost(){CompanyId="com1",CompanyJobPostId="com1jp2",CreatedOn=System.DateTime.Now.AddDays(-3),JobDiscription="Developer",KeySkils="C#"},
new CompanyJobPost(){CompanyId="com2",CompanyJobPostId="com2jp1",CreatedOn=System.DateTime.Now.AddDays(-5),JobDiscription="Tester",KeySkils="Sylanium"},
new CompanyJobPost(){CompanyId="com2",CompanyJobPostId="com2jp2",CreatedOn=System.DateTime.Now.AddDays(-6),JobDiscription="Developer",KeySkils="C#"},
new CompanyJobPost(){CompanyId="com3",CompanyJobPostId="com3jp1",CreatedOn=System.DateTime.Now.AddDays(-7),JobDiscription="Tester",KeySkils="Sylanium"},
new CompanyJobPost(){CompanyId="com3",CompanyJobPostId="com3jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils="C#"}
};
var InstituteJobPosts = new List<InstituteJobPost>()
{
new InstituteJobPost(){InstituteId="ins1",InstituteJobPostId="ins1jp1",CreatedOn=System.DateTime.Now.AddDays(-1),JobDiscription="Trainer",KeySkils="C#",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins1",InstituteJobPostId="ins1jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils="Java",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins2",InstituteJobPostId="ins2jp1",CreatedOn=System.DateTime.Now.AddDays(-1),JobDiscription="Trainer",KeySkils="Java",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins2",InstituteJobPostId="ins2jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils=".Net",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins3",InstituteJobPostId="ins3jp1",CreatedOn=System.DateTime.Now.AddDays(-1),JobDiscription="Trainer",KeySkils="C#",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins3",InstituteJobPostId="ins3jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils="Java",ExtraField="MDifferent"}
};
var allJobPosts=new List<object>();
foreach (var item in CompanyJobPosts)
{
allJobPosts.Add(new { JType = "Company", JobPost = item });
}
foreach (var item in InstituteJobPosts)
{
allJobPosts.Add(new { JType = "Institute", JobPost = item });
}
//var allJobPostsOrderdByDate=??
return Json(allJobPosts, JsonRequestBehavior.AllowGet);
}
Here are My Models just to make it simple.
namespace WebApplication1.Models
{
public class Company
{
public string CompanyId { get; set; }
public string CompanyName { get; set; }
public string Location { get; set; }
}
public class Organization
{
public string OrganizationId { get; set; }
public string OrganizationName { get; set; }
public string Location { get; set; }
}
public class Institute
{
public string InstituteId { get; set; }
public string InstituteName { get; set; }
public string Location { get; set; }
}
public class CompanyJobPost
{
public string CompanyJobPostId { get; set; }
public string CompanyId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
}
public class OrganizationJobPost
{
public string OrganizationJobPostId { get; set; }
public string OrganizationId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField2 { get; set; }
}
public class InstituteJobPost
{
public string InstituteJobPostId { get; set; }
public string InstituteId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField { get; set; }
}
}
And finally my sweet view
<input name="GetAllJobPosts" id="GetAllJobPosts" type="submit" value="Search Jobs">
<ul id="JobPostList"></ul>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$("#GetAllJobPosts").click(function () {
var actionUrl = '#Url.Action("GetAllJobPosts", "Default")';
$.getJSON(actionUrl, displayDetailData);
});
function displayDetailData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#JobPostList").append("<li>" + response[i].JType + " " + (response[i].JobPost).CreatedOn + "</li>")
}
}
}
Thank You!
Based on your comments, I can only assume the following, so will do my best to point you in the correct direction:
You do not have a common object of inheritance between the two - that is, you wish to sort them on property x, but property x, is not defined to exist in both.
So, solution? Easy: add a common interface, class or abstract class between the two that has the property you wish to sort by, then sort by it:
public interface IJobPost
{
DateTime CreatedOn { get; set; }
}
Then modify your three existing objects:
public class CompanyJobPost : IJobPost
{
public string CompanyJobPostId { get; set; }
public string CompanyId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
}
public class OrganizationJobPost : IJobPost
{
public string OrganizationJobPostId { get; set; }
public string OrganizationId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField2 { get; set; }
}
public class InstituteJobPost : IJobPost
{
public string InstituteJobPostId { get; set; }
public string InstituteId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField { get; set; }
}
Lastly, the action:
var allJobPosts=new List<IJobPost>();
// Add other posts to allJobPosts here.
var allJobPostsOrderdByDate = allJobPosts.OrderBy(x => x.CreatedOn).ToList();
Note: Code is untested. LINQ query may or may not work. Did this all from memory.
Edit: You can also share any other properties you wish to force between the three of them. That is what an interface or abstract class is for. That also means you can share Description or other properties.
I'm having the strangest problem and I know it's because I'm missing something obvious because this set up works fine when I save data and even pull it down.
My app is set up like so ....
WebUI depends on Business Layer .. Business Layer depends on Data Layer (which is where I'm actually pulling the data). The Business Layer does all the "work".
This is where everything dies (Null Exception, Object Reference not set) as soon as I assign something to userInfo.userData.avatarFilepath (which is not null).
namespace pgl.businesslayer
{
public class userCtx
{
private pgl.datalayer.Concrete.EFDbContext context = new pgl.datalayer.Concrete.EFDbContext();
private pgl.datalayer.Concrete.EFUserContext userContext = new pgl.datalayer.Concrete.EFUserContext();
private pgl.datalayer.Concrete.EFDbCompany companyContext = new pgl.datalayer.Concrete.EFDbCompany();
public ViewModels.UserInfo getUserById(int userId)
{
ViewModels.UserInfo userInfo = new ViewModels.UserInfo();
pgl.datalayer.Dtos.pglUserDTO userDL = userContext.getUserByUserId(userId);
userInfo.userData.avatarFilepath = userDL.avatarFilepath;
userInfo.userData.createdBy = userDL.createdBy;
userInfo.userData.createdDate = userDL.createdDate;
userInfo.userData.email = userDL.email;
userInfo.userData.firstName = userDL.firstName;
userInfo.userData.lastName = userDL.lastName;
etc...
}
ViewModels.UserInfo looks like this...
namespace pgl.businesslayer.ViewModels
{
public class UserInfo
{
// user info
public pgl.businesslayer.Dto.pglUser userData { get; set; }
// salon info
public List<pglSalon> salonsData { get; set; }
// company info
public pglCompany companyData { get; set; }
}
pglUser in the business layer looks like this and is just a POCO
namespace pgl.businesslayer.Dto
{
public class pglUser
{
public int userId { get; set; }
public int companyId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string username { get; set; }
public byte[] passwordSalt { get; set; }
public byte[] passwordKey { get; set; }
public DateTime createdDate { get; set; }
public int createdBy { get; set; }
public bool passwordResetRequired { get; set; }
public string passwordHash { get; set; }
public string tempPassword { get; set; }
public string userType { get; set; }
public string avatarFilepath { get; set; }
public string timeZone { get; set; }
}
}
And in userContext this is how I am pulling the user data...
public pgl.datalayer.Dtos.pglUserDTO getUserByUserId(int userId)
{
var getUser = (from u in context.pglUser
select new pgl.datalayer.Dtos.pglUserDTO
{
username = u.username,
companyId = u.companyId,
userId = u.userId,
userType = u.userType,
firstName = u.firstName,
lastName = u.lastName,
email = u.email,
createdDate = u.createdDate,
createdBy = u.createdBy,
passwordResetRequired = u.passwordResetRequired,
tempPassword = u.tempPassword,
avatarFilepath = u.avatarFilepath,
timeZone = u.timeZone
}).Where(u => u.userId == userId).FirstOrDefault();
return getUser;
}
pgl.datalayer.Dtos.pglUserDTO looks like this...
namespace pgl.datalayer.Dtos
{
public class pglUserDTO
{
public int userId { get; set; }
public int companyId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string username { get; set; }
public byte[] passwordSalt { get; set; }
public byte[] passwordKey { get; set; }
public DateTime createdDate { get; set; }
public int createdBy { get; set; }
public bool passwordResetRequired { get; set; }
public string passwordHash { get; set; }
public string tempPassword { get; set; }
public string userType { get; set; }
public string avatarFilepath { get; set; }
public string timeZone { get; set; }
}
}
Even if I assign userInfo.userData.avatarFilepath = "WHATUP!!!" it throws the same error. This has got to be something stupid and simple. I can save data with no problem and when I debug I can see that it is actually pulling the correct user ID and it's associated data. It's just that pgl.businesslayer.ViewModels.UserInfo seems to be un-instantiated. I'm at a loss. I can provide more info... and keep in mind I'm kind of at my wits end so I tried doing weird things like adding (probably) unnecessary DTOs. Any ideas?
You don't appear to be creating the userData object anywhere. When you create a new instance of UserInfo, or in its constructor, try adding:
userData = new pgl.businesslayer.Dto.pglUser();
Or alternatively:
ViewModels.UserInfo userInfo = new ViewModels.UserInfo();
pgl.datalayer.Dtos.pglUserDTO userDL = userContext.getUserByUserId(userId);
userInfo.userData = new pgl.businesslayer.Dto.pglUser {
avatarFilepath = userDL.avatarFilepath,
createdBy = userDL.createdBy,
createdDate = userDL.createdDate,
email = userDL.email,
firstName = userDL.firstName,
lastName = userDL.lastName
};
If you always want to initialise UserInfo with an empty userData member, you could include the creation within the constructor:
namespace pgl.businesslayer.ViewModels
{
public class UserInfo
{
// Default constructor
public UserInfo()
{
userData = new pgl.businesslayer.Dto.pglUser();
}
// user info
public pgl.businesslayer.Dto.pglUser userData { get; set; }
// salon info
public List<pglSalon> salonsData { get; set; }
// company info
public pglCompany companyData { get; set; }
}
}
In my application I want to retrieve blind_copy_recipients from system table 'sysmail_mailitems' from database 'MSDB' in SQL Server 2012. I am using Entity Framework in a C# web application to query databases. I created a class for sysmail_mailitems and method to read data from it. But it actually created a new table outside of system tables with this name. My goal is not to create a table but just to read from existing table. Can anyone please guide me on how could I do it?
Code:
public class sysmail_mailitem
{
[Key]
public Int32 mailitem_id { get; set; }
public Int32 profile_id { get; set; }
public String recipients { get; set; }
public String copy_recipients { get; set; }
public String blind_copy_recipients { get; set; }
public String subject { get; set; }
public String from_address { get; set; }
public String reply_to { get; set; }
public String body { get; set; }
public String body_format { get; set; }
public String importance { get; set; }
public String sensitivity { get; set; }
public String file_attachments { get; set; }
public String attachment_encoding { get; set; }
public String query { get; set; }
public String execute_query_database { get; set; }
public Boolean? attach_query_result_as_file { get; set; }
public Boolean? query_result_header { get; set; }
public Int32? query_result_width { get; set; }
public String query_result_separator { get; set; }
public Boolean? exclude_query_output { get; set; }
public Boolean? append_query_error { get; set; }
public DateTime send_request_date { get; set; }
public String send_request_user { get; set; }
public Int32? sent_account_id { get; set; }
public Byte? sent_status { get; set; }
public DateTime? sent_date { get; set; }
public DateTime last_mod_date { get; set; }
public String last_mod_user { get; set; }
}
public String GetMailRecipients(Int32 mailItemId)
{
using(MSDBContext _db = new MSDBContext())
{
var query = (from mailItems in _db.MailItems
where mailItems.mailitem_id == mailItemId
select mailItems).FirstOrDefault();
try
{
return query.blind_copy_recipients;
}
catch (NullReferenceException) { }
return "N/A";
}
}
public class MSDBContext : DbContext
{
public MSDBContext() : base("msdb") { }
public DbSet<sysmail_mailitem> MailItems { get; set; }
}
In the end I came up with executing raw sql command using ExecuteStoreQuery to retrieve data from MSDB.
Code:
public String GetMailRecipients(Int32 mailItemId)
{
using(context _db = new context())
{
var obj = ((IObjectContextAdapter)_db).ObjectContext;
return obj.ExecuteStoreQuery<String>("SELECT blind_copy_recipients FROM msdb.dbo.sysmail_mailitems WHERE mailitem_id = {0}", mailItemId).FirstOrDefault();
}
}
If you want to do it the initial way you tried, using DBSet etc you can do that. Your issue is that you called the class sysmail_mailitem when the table name is sysmail_mailitems (with an s). So you would have to annotate the actual table name above the class like this:
[Table("sysmail_mailitems")]
public class sysmail_mailitem
{
I am creating a web application and I have two classes:
public class MOrderMain
{
public int ID { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public DateTime OrderDate { get; set; }
public string BillingName { get; set; }
public string BillingAddress { get; set; }
public string DeliveryName { get; set; }
public string DeliveryAddress { get; set; }
}
public class MOrder
{
public int ID { get; set; }
public int OrhID { get; set; }
public int ProID { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public double Amount { get; set; }
public int DeliveredQty { get; set; }
}
I would like to retrieve details from both classes. For example, I want to get
ID and Billing Name from class MorderMain and all the properties from class MOrder. How can I do this?
I am getting the values by database. I have the query but how will I assign the data and how will I retrieve from both?
var mylist = new List<MOrder>();
_con = _db.GetConnection();
if (_con.State.Equals(ConnectionState.Closed))
{
_con.Open();
}
_cmd = new SqlCommand("Get_All_Order_Details", _con)
{ CommandType = CommandType.StoredProcedure };
_dr = _cmd.ExecuteReader();
while (_dr.Read())
{
mylist.Add(new MOrder
{
ID = Convert.ToInt32(_dr["ordID"]),
OrhID = Convert.ToInt32(_dr["orhID"]),
ProID = Convert.ToInt32(_dr["proID"]),
Name = _dr["pName"].ToString(),
Quantity = Convert.ToInt32(_dr["ordQty"]),
Rate = Convert.ToDouble(_dr["ordRate"]),
Amount = Convert.ToDouble(_dr["ordAmount"]),
DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
});
}
return mylist;
Since you are retrieving data from both tables in your database but want to combine them in your application, the solution would be to create a single class that contains the data you return from your stored procedure:
public class MAllOrderDetails
{
public int ID { get; set; }
public string BillingName { get; set; }
// include the other billing details you want here
public int OrhID { get; set; }
public int ProID { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public double Amount { get; set; }
public int DeliveredQty { get; set; }
}
Then, your query changes to filling in a List<MAllOrderDetails>.
This leaves your application with only dealing with a collection of a single class with all the data nicely contained in single objects.
var mylist = new List<MAllOrderDetails>();
//...
while (_dr.Read())
{
mylist.Add(new MAllOrderDetails
{
ID = Convert.ToInt32(_dr["ordID"]),
BillingName = _dr["BillingName"].ToString(),
// etc.
OrhID = Convert.ToInt32(_dr["orhID"]),
ProID = Convert.ToInt32(_dr["proID"]),
Name = _dr["pName"].ToString(),
Quantity = Convert.ToInt32(_dr["ordQty"]),
Rate = Convert.ToDouble(_dr["ordRate"]),
Amount = Convert.ToDouble(_dr["ordAmount"]),
DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
});
}
Update
You could probably get away with this as the closest solution to not creating an additional classes:
class MAllOrderDetails
{
public MOrder Order { get; set; }
public MOrderMain OrderMain { get; set; }
}
I feel, though, that from a maintainability standpoint, this will cause you more headaches than just creating additional classes.