I am attempting to Query a database and store those results in a model, one of the columns is numerical and one is string data:
Model:
using System.Data.Entity;
namespace Portal.Models
{
public class CompanyListId
{
public int Id { get; set; }
public string CompanyName { get; set; }
}
public class CompanyListIdDbContext : DbContext
{
public DbSet<CompanyListId> Contacts { get; set; }
}
}
Controller:
public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new { p.CoId, p.CompanyName };
}
//I want to set Models ID = to each instance of coid
//Set Models CompanyName to each instance of companyname
return PartialView();
}
I am not sure where to go from here, I am attempting to make a drop down from this model.
I updated my code block to:
public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
return PartialView(content.ToList());//giving an error
}
}
And my view to:
#model Portal.Models.CompanyListId
#Html.DropDownListFor(m => m.CompanyName, Model.CompanyName)
This also doesn't seem to work, I need to return my Model from the action I would think, that way the view can properly use the data.
You should project the result to your class CompanyListId
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
EDIT:
I am not sure about the error, but you can try :
public PartialViewResult SelectCompanyFromDropdown()
{
List<CompanyListId> content = null;
using (var dc = new CompanyListIdDbContext())
{
content = (from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
}).ToList();
}
return PartialView(content);
}
You can just select a new instance of your class like so:
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
Related
Initially I was using automapper for this but its seems way harder for me to implement it.
Basically, I just want to return an empty list instead of null values. I can do this on projects level but not on teammates level. The API must not return a null because the UI that consumes it will have an error.
Sample of my implementation below:
Projects = !Util.IsNullOrEmpty(x.Projects) ? x.Projects : new List<ProjectsDto>(),
Ill highly appreciate if someone can guide me on how to manually map this with null/empty checking.
If you can also provide and example using automapper that too will be very helpful.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public List<ProjectsDto> Projects { get; set; }
}
public class ProjectsDto
{
public string Status { get; set; }
public List<TeammatesDto> Teammates { get; set; }
}
public class TeammatesDto
{
public string TeammateName { get; set; }
public string PreviousProject { get; set; }
}
//Get by Id
var employee = await _context.Employees
.Where(x => x.id.Equals(request.Id)
.FirstOrDefaultAsync(cancellationToken);
//Map employee
EmployeeDto ret = new EmployeeDto()
{
Id = employee.id,
Name = employee.Name,
Projects = null //TODO: map manually
}
//Get all employees
var employees = await _context.Employees.AsNoTracking()
.ToListAsync(cancellationToken);
//Map here
IList<EmployeeDto> list = new List<EmployeeDto>();
foreach (var x in employees)
{
EmployeeDto dto = new EmployeeDto()
{
Id = x.id,
Name = x.Name,
Projects = null //TODO: map manually
};
list.Add(dto);
}
return list;
Instead of materializing full entities, do the following:
var query = _context.Employees
.Select(e = new EmployeeDto
{
Id = e.id,
Name = e.Name,
Projects = e.Projects.Select(p => new ProjectDto
{
Status = p.Status,
Templates = p.Templates.Select(t => new TemplateDto
{
TeammateName = t.TeammateName,
PreviousProject = t.PreviousProject
}).ToList()
}).ToList()
}
);
var result = await query.ToListAsync();
I have the following method to return the data of two entities.
public List<Object> GetDados()
{
var sendFilter = new Filter<MessageSent>();
//employeeFilter.Add(x => x.Name, name);
sendFilter.Add(x => x.MessageSentSeq, ID_GROUP_SEND);
// You can add more filters
MessageSentService svc = new MessageSentService();
var messages = svc.Find(sendFilter).ToList();
var employees = new EmployeeService().GetAll();
var query =
from employee in employees
join message in messages
on employee.EmployeeId equals message.EmployeeId
select new
{
MessageSentId = message.MessageSentId,
//EmployeeId = message.EmployeeId,
//MessageSentSeq = message.MessageSentSeq,
Name = employee.Name,
Surname = employee.Surname,
Mobile = employee.Mobile,
Email = employee.Email,
Status = "N"
};
return query.ToList<Object>();
}
Call
ILog log = LogManager.GetLogger(typeof(Form));
List<Object> Send;
Send = GetDados();
gvSent.DataSource = Send;
When doing send I would like to update the record that is inside object var query that in turn populates my grid
I need to set the status field with S at the end of everything I updated my database with the items that were sent correctly.
Because your function returns a List<Object>, you'll be unable to modify those properties without using Reflection or some other drastic measure. If you plan on this data being modifiable, you'll need to make sure the data you're returning is typed. First define a simple class:
class Dado
{
public string MessageSentId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public bool Mobile { get; set; }
public string Email { get; set; }
public string Status { get; set; }
}
...then modify your function to return instances of this type:
public List<Dado> GetDados()
{
var sendFilter = new Filter<MessageSent>();
//employeeFilter.Add(x => x.Name, name);
sendFilter.Add(x => x.MessageSentSeq, ID_GROUP_SEND);
// You can add more filters
MessageSentService svc = new MessageSentService();
var messages = svc.Find(sendFilter).ToList();
var employees = new EmployeeService().GetAll();
return (
from employee in employees
join message in messages
on employee.EmployeeId equals message.EmployeeId
select new Dado
{
MessageSentId = message.MessageSentId,
//EmployeeId = message.EmployeeId,
//MessageSentSeq = message.MessageSentSeq,
Name = employee.Name,
Surname = employee.Surname,
Mobile = employee.Mobile,
Email = employee.Email,
Status = "N"
}
).ToList();
}
Now, in your code after populating the grid can do something like:
foreach (var dado in Send) {
dado.Status = "S";
}
Below is the error i getting :
The model item passed into the dictionary is of type 'System.Collections.Generic.List[StoredProcedureEF_MVC.tbl_users]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable[StoredProcedureEF_MVC.Models.User]'.
I have tried a lot but don't know where i was doing wrong, no luck from last two days. I am learning MVC, so sorry if you got some stupid mistake.
My Model :
namespace StoredProcedureEF_MVC.Models
{
[Table("tbl_users")]
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public string Username {get;set;}
[Required]
public string Email { get; set; }
}
}
VIEW:
#model IEnumerable<StoredProcedureEF_MVC.Models.User>
#{
ViewBag.Title = "Delete";
}
#{
var grid = new WebGrid(source: Model);
}
#grid.GetHtml(
columns: grid.Columns(
grid.Column("UserID"),
grid.Column("Username"),
grid.Column("Email"),
grid.Column(
format: (item) => Html.ActionLink("Delete", "DeleteUser", new {id=item.UserID })
)
)
)
CONTROLLER ACTION:
[HttpGet]
public ActionResult Delete()
{
SPEFMVCEntities conn = new SPEFMVCEntities();
var result = (from p in conn.tbl_users select p).ToList();
return View(result);
}
try
var result = conn.tbl_users.Select(c => new StoredProcedureEF_MVC.Models.User
{
UserId = c.UserId,
UserName = c.UserName,
Email = c.Email
}).ToList();
return View(result);
Try to change your controller method to this:
[HttpGet]
public ActionResult Delete()
{
SPEFMVCEntities conn = new SPEFMVCEntities();
var result = (from p in conn.tbl_users select p as StoredProcedureEF_MVC.Models.User).ToList();
return View(result);
}
I have two DTOs:
public class MasterDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<DetailDTO> Details { get; set; }
}
public class DetailDTO
{
public int Id { get; set; }
public string DetailName { get; set; }
}
Also, I have a function:
using (var context = new Context())
{
var r = context.MasterData
.Select(d => new MasterDTO
{
Id = d.Id,
Name = d.Name,
}
}
I need to fill the list of DetailDTOs too and do it in a single request.
At this moment, I have to get list of DetailsData data and add it through foreach to the MasterDTO, which, of course causes a lot of requests to the database server.
Is there a better solution?
In your data call, do an eager load on your DetailData.
Example:
var r = context.MasterData.Include("DetailData")
DetailData should be the name of your navigation property attached to your MasterData entity.
This will cause detail data to be pulled along with your call for MasterData.
The full call may look something like this:
using (var context = new Context())
{
context.LazyLoadingEnabled = false;
var r = context.MasterData.Include("DetailData")
.Select(d => new MasterDTO()
{
Id = d.Id,
Name = d.Name,
Details = d.Details.Select(dt => new DetailDTO()
{
Id = dt.Id,
DetailName = dt.DetailName
})
});
}
Looking for an example where I can filter my collection based on some filtering criteria.
I have been looking for some example where given a list /array i can filter a collection.
In the example below in my find method I am trying to filter based on 2 values ,looking for something like an "IN" function any suggestions?
class Program
{
static void Main()
{
//Print all customres that belong to below deparments and match on surname
var criteria=new Criteria
{
Departments = new List<string> {"BusinessAnalyst", "Account"},
Surname = "Bloggs"
};
List<Customer> customers = Repository.Find(criteria);
customers.ForEach(x => Console.WriteLine(string.Format("Surname: {0} Department :{1}", x.Surname,x.Department)));
Console.Read();
}
}
public class Repository
{
public static List<Customer>GetCustomers()
{
return new List<Customer>
{
new Customer { Name = "Jon",Surname="Smith",Department = DepartmentType.Managers},
new Customer{Name = "Bill",Surname = "Gates",Department = DepartmentType.Managers},
new Customer { Name = "Mary",Surname = "Bug",Department = DepartmentType.Developers},
new Customer { Name = "Mark",Surname="Boo",Department = DepartmentType.Account},
new Customer{Name = "Ron",Surname = "Scott",Department = DepartmentType.Managers},
new Customer { Name = "Jonny",Surname = "Dip",Department = DepartmentType.Developers},
new Customer { Name = "Mary",Surname = "Bloggs",Department = DepartmentType.BusinessAnalyst},
new Customer { Name = "Mary",Surname = "Bug",Department = DepartmentType.Account},
new Customer { Name = "Jonny",Surname = "Dip",Department = DepartmentType.Account},
new Customer { Name = "Mary",Surname = "Bloggs",Department = DepartmentType.Managers}
};
}
public static List<Customer> Find(Criteria criteria)
{
List<Customer>customers=Repository.GetCustomers();
//Filter on departments
//ERROR HERE AS I cannot do this "IN" would be fantastic.
customers = customers.Contains(criteria.Departments);
//now filter on name
customers = customers.Where(x => x.Surname == criteria.Surname).ToList();
return customers;
}
}
public enum DepartmentType
{
Account,
Managers,
Developers,
BusinessAnalyst
}
public class Customer
{
public string Name { get; set; }
public string Surname { get; set; }
public DepartmentType Department { get; set; }
}
public class Criteria
{
public Criteria()
{
Departments=new List<string>();
}
public string Name { get; set; }
public string Surname { get; set; }
public List<string> Departments { get; set; }
}
public static List<Customer> Find(Criteria criteria)
{
List<Customer> customers = Repository.GetCustomers();
var customers2 = customers.Where(x => criteria.Departments.Contains(x.Department.ToString()));
var customers3 = customers2.Where(x => x.Surname == criteria.Surname);
return customers3.ToList();
}
But considering you use an enum for the Department (DepartmentType), shouldn't your Criteria class use the same instead of a string?
If you define the criteria.Departments as List<DepartmentType> then you can write
public static List<Customer> Find(Criteria criteria)
{
List<Customer> customers = Repository.GetCustomers();
var customers2 = customers.Where(x => criteria.Departments.Contains(x.Department));
var customers3 = customers2.Where(x => x.Surname == criteria.Surname);
return customers3.ToList();
}
Contains returns a bool defining whether a specified object is contained in a collection. Based on your example, you will need to use Where to filter the customers, then use Contains on the departments:
customers = customers.Where(c => criteria.Departments.Contains(c.Department));
i think you want something like this..
customers = customers.Where(c => criteria.Departments.Contains(c.Department));
You want
Customers.Where(c => criteria.Departments.Contains(c.Department.ToString()))
Not sure if this is what you're looking for but the following:
List<Customer> FilteredCustomers = (from c in customers where Criteria.Departments.Contains(c.deparment) && c.surname == Criteria.Surname select c).ToList();
Would equate to something like this in SQL:
SELECT *
FROM Customers
WHERE Department IN (
List of departments
)
AND Surname = surname
I haven't tested this but I think it should work and bring back what you want.