Here is my problem step by step,
1- I do ajax get request from my external javascript file as following,
$.ajax({
type: "GET",
dataType: 'json',
url: '/Company/GetCompanies',
error: function (xhr, status, error) {
alert('error');
return false;
},
success: function (response) {
alert('success');
return false;
}
});
2 – This is the action method that receives the request
public ActionResult GetCompanies()
{
var model = new CompanyIndex();
model.FillCompanies();
return Json(model ,JsonRequestBehavior.AllowGet);
}
3 – CompanyIndex is a ViewModel that is created in my action method above.
public class CompanyIndex
{
public IList<Company> Companies { get; set; }
public void FillCompanies()
{
/* Part that is not working */
UnitOfWork unitOfWork = new UnitOfWork();
Companies = unitOfWork.CompanyRepository
.Get(orderBy: q => q.OrderBy(u => u.CompanyName)).ToList();
unitOfWork.Dispose();
/****************************/
/* This works fine */
var companyList = unitOfWork.CompanyRepository
.Get(orderBy: q => q.OrderBy(u => u.CompanyName)).ToList();
Companies = companyList.Select(x => new { name = x.CompanyName }).ToList()
.Select(x => new Company
{
CompanyName = x.name
}).ToArray<Company>();
/********************/
}
}
As you can see I fetch company entities from the database using my repository and Get method that I also share below. The problem is when I fetch them from database, the type of the model that is retrieved is System.Data.Entity.DynamicProxies.Company_someRandomStringHere. In this case Ajax get request does not succeed and alerts error message.
However, if I first fetch from db and create Company objects in ViewModel and assign them to my List, ajax works fine, and ajax get request returns success. And type of Company entities when I create objects at ViewModel is CompanyManagement.Models.Company as it should be.
Just in case you need it this is the Get method I am using to fetch data from db.
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
query = query.Where(filter);
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
query = query.Include(includeProperty);
if (orderBy != null)
return orderBy(query).ToList();
else
return query.ToList();
}
I don’t want to manually create new Company objects. Any ideas are really appreciated. Thanks in advance.
Found the problem. It seems the respond of Ajax request needs to be serializable. To do that, I canceled dynamic proxies with,
As a result my Get function now returns
CompanyManagement.Models.Companyentities instead ofSystem.Data.Entity.DynamicProxies.Company.Edit:
Use viewmodels to populate your views, do not return entities keeping your business logic to client side. This is bad practice and dangerous in some cases.