we are working on api creation using asp.net core web api and mysql as backend. i need to maintain this architecture and and also need to join table. i have tried many ways still stuck in middle.
public class CallLogs:AuditableEntity
{
public int CallTypeId { get; set; }
public virtual CallType CallType { get; set; }
public virtual ICollection<CallType> CallTypes { get; set; }
public int PatientId { get; set; }
public int AgentId { get; set; }
public string CallDuration { get; set; }
public DateTime Date { get; set; }
public int ServiceId { get; set; }
public string Message { get; set; }
//public virtual Patient Patient { get; set; }
//public virtual Service Service { get; set; }
}
this calllogs has many tables foreign key and i want to retrieve some columns from each table. so how should i retrieve? in this project we added mapper classes and response and request classes
public class CallType:AuditableEntity
{
public string Name { get; set; }
public virtual ICollection<CallLogs> CallLogs { get; set; }
}
and made service where i including the tables
private ISpecification<CallLogs> GetSpecification(Expression<Func<CallLogs, bool>>
expression = null, string sortField = "none", int sortOrder = -1)
{
if (expression == null)
expression = v => v.IsDeleted != true;
Infrastructure.Specifications.BaseSpecification<CallLogs> specification =
new
Infrastructure.Specifications.BaseSpecification<CallLogs>(expression);
//specification.IncludeExp = p => p.Include(x => x.Patient);
specification.IncludeExp = p => p.Include(x => x.CallType);
// specification.IncludeExp = p => p.Include(x => x.Service);
if (sortField != "none" && !string.IsNullOrEmpty(sortField))
specification.OrderByDescending = p => p.GetSortOrder(sortField,
sortOrder);
else
specification.OrderByDescending = p => p.OrderByDescending(p =>
p.IsActive)
.ThenByDescending(p => p.CreatedDate)
.ThenByDescending(p => p.Id);
specification.IsPagingEnabled = true;
specification.Skip = (pageNo - 1) * pageSize;
specification.Take = pageSize;
return specification;
}
and we are calling this function in the getall api
public async Task<EntityResponseModel> GetAllAsync(int pageNo = 1, int pageSize = 10)
{
var callLogsResponse = new List<CallLogsResponse>();
this.pageNo = pageNo;
this.pageSize = pageSize;
var callLogs = (await repository.FindAsync(GetSpecification())).ToList();
// .Select(s => new
// {
// Name = s.CallType.Name,
// PateintId = s.PatientId,
// AgentId = s.AgentId,
// CallDuration = s.CallDuration,
// Date = s.Date,
// ServiceId = s.ServiceId,
// Message = s.Message,
// Id = s.Id,
// IsActive = s.IsActive
// }).ToList() ;
int count = await repository.CountAsync(v => !v.IsDeleted);
var _pages = Math.Round(count / (double)pageSize,
MidpointRounding.ToPositiveInfinity);
var statusCode = 200;
callLogsResponse = _mapper.Map<List<CallLogs>, List<CallLogsResponse>>
(callLogs);
return new EntityResponseModel
{
APIResponse =
APIResponseHelper.Getinstance().ConvertToAPIResponse(callLogsResponse,
string.Empty,statusCode, Convert.ToInt32(_pages),
Convert.ToInt32(count)),
Entity = callLogs,
EntityResponse = callLogsResponse
};
}
how do i join table and column what i need?
Related
Platform:
Blazor, EF Core 6
When sending an OData filter query to my server, it works for some properties and fails for others, although they have the same type.
public partial class DocumentRequestDTO
{
public DocumentRequestDTO()
{ }
[Key]
public Guid ID { get; set; }
public string AuthorID { get; set; } = string.Empty;
public string Authorname { get; set; } = string.Empty;
public Guid DocumentID { get; set; } = Guid.Empty;
public string OwnerID { get; set; } = string.Empty;
public string Ownername { get; set; } = string.Empty;
public string Filename { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string ReasonForRequest { get; set; } = string.Empty;
public string WatermarkText { get; set; } = string.Empty;
public bool IsForInternalUse { get; set; } = false;
public DateTime TimeStamp { get; set; } = DateTime.Now;
public string ReasonForDecision { get; set; } = string.Empty;
public string Statusname { get; set; } = string.Empty;
public List<ProxyTooltipData>? Proxies { get; set; } = null;
}
}
Controller code:
[EnableQuery]
public IQueryable<DocumentRequestDTO> GetForSelect(string userID, bool showByAuthor)
{
IQueryable<DocumentRequest> qBase = null!;
try
{
qBase =
_context.Requests
.Include(r => r.Document)
.ThenInclude(d => d.Owner)
.Include(r => r.Author)
.Where(r => r.TimeStamp.Date >= DateTime.Today.AddDays(-ServerGlobals.RequestLifespan))
;
}
catch (Exception e)
{
Console.WriteLine($"Error '{e.Message}' occurred while quyering requests.");
}
UserInfo user = _context.UserInfo.FirstOrDefault(e => e.AccountID == userID);
if ((user != null) && (user.AccessLevel < AccessLevels.Admin))
{
try
{
if ((user.AccessLevel == AccessLevels.Requester) || showByAuthor)
{
qBase = qBase.Where(x => x.AuthorID == user.AccountID);
}
else
{
List<string> proxiedOwners = new();
foreach (var p in _context.ProxyInfo.Where(p => p.ProxyID == user.AccountID).ToList())
proxiedOwners.Add(p.AccountID);
qBase = qBase.Where(x => proxiedOwners.Contains(user.AccountID));
}
}
catch (Exception e)
{
Console.WriteLine($"Error '{e.Message}' occurred while determining proxied owners.");
}
}
IQueryable<DocumentRequestDTO> qFinal = null!;
try
{
qFinal = qBase
.Select(
x => new DocumentRequestDTO()
{
ID = x.ID,
AuthorID = x.AuthorID,
TimeStamp = x.TimeStamp,
DocumentID = x.Document.ID,
Filename = (x.Document == null) ? "unknown" : x.Document.Filename,
OwnerID = x.Document.OwnerID,
Ownername = x.Document.Owner.Name,
Authorname = x.Author.Name,
Description = x.Document.Description,
WatermarkText = x.WatermarkText,
ReasonForRequest = x.ReasonForRequest,
ReasonForDecision = x.ReasonForDecision,
IsForInternalUse = x.IsForInternalUse,
ReviewStatus = x.ReviewStatus,
Statusname = DocumentRequest.StatusName(x.ReviewStatus),
Proxies = new()
});
}
catch (Exception e)
{
Console.WriteLine($"Error '{e.Message}' occurred while building request result.");
}
List<DocumentRequestDTO> l = null!;
try
{
l = qFinal.ToList();
}
catch (Exception e)
{
Console.WriteLine($"Error '{e.Message}' occurred while verifying request result.");
}
return qFinal;
}
StatusName code:
public enum RequestStatus
{
Pending,
Approved,
Declined,
NoDecisionNeeded
}
public class DocumentRequest : PropertyIndexer
{
public static string StatusName(RequestStatus status)
{
switch (status)
{
case RequestStatus.Pending:
return "Pending";
case RequestStatus.Approved:
return "Approved";
case RequestStatus.Declined:
return "Declined";
case RequestStatus.NoDecisionNeeded:
return "No decision needed";
default:
return "unknown";
}
}
}
Working request:
https://localhost:12345/TestServer/RequestDto
?$count=true&$orderby=Ownername&$select=Ownername&userID=0388&showByAuthor=False
Result:
{#odata.context: "https://localhost:44393/DocServer2/$metadata#RequestDto(Ownername)", #odata.count: 4,…}
#odata.context: "https://localhost:44393/DocServer2/$metadata#RequestDto(Ownername)"
#odata.count: 4
value: [{Ownername: "Baggins, Frodo"},
{Ownername: "Baggins, Frodo"},
{Ownername: "Wonka, Willy"},…]
0: {Ownername: "Baggins, Frodo"}
1: {Ownername: "Baggins, Frodo"}
2: {Ownername: "Wonka, Willy"}
3: {Ownername: "Wonka, Willy"}
Failed request:
https://localhost:12345/TestServer/RequestDto
?$count=true&$orderby=Filename&$select=Filename&userID=0388&showByAuthor=False
Result:
{"#odata.context":"https://localhost:44393/DocServer2/$metadata
#RequestDto(Filename)",
"#odata.count":4,"value":[
The underlying data from the controller: (from the list l)
The error occurs when selecting Filename or Statusname. I found that when assigning constant values to these properties ("Testfile.pdf" and "Test Status") the error does not appear. However, the data returned from my controller is complete and cointains valid filenames for all records returned, and there are no exceptions thrown during execution of my controller's code; Not even when getting a list of the data from the query result.
Regarding Statusname: If you check my below related code, you will notice that there will always valid string data assigned to it.
I found the problem myself: It is the assignment of
Statusname = DocumentRequest.StatusName(x.ReviewStatus)
in the controller.
When OData tries to retrieve data using the IQueryable my controller returns, it fails to invoke that static class member, because it expects a property from a database table here.
Now the question is whether there is a workaround for that not requring adding database table properties, because I would like to display a user readable version of the data's ReviewStatus property.
I have a simple table which I can perform Inser and Read operations using MySQL Commands.
For some reason, when using Linq2DB I get the following ERROR:
Connection option 'datasource' is duplicated.
at MySql.Data.MySqlClient.MySqlBaseConnectionStringBuilder.AnalyzeConnectionString
This Works:
private void BulkInsert(List<string> rows)
{
var commandText = new StringBuilder("INSERT INTO cloudevents (JobId, Name, ErrorUrgency, EventCategory, EventType, Time, Parameters) VALUES ");
commandText.Append(string.Join(",", rows));
commandText.Append(";");
try
{
using (MySqlCommand command = MySqlConnectionConnector.CreateCommand())
{
command.CommandText = commandText.ToString();
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e);
throw;
}
finally
{
rows.Clear();
}
}
This Throw Error:
using (var db = new EocIpcDB())
{
db.Insert(new EventsOnCloudData()
{
JobId = 2000,
ErrorUrgency = "Error",
EventCategory = "HW",
EventType = "Disk",
Name = "Haedware Events",
Time = DateTime.Now,
Parameters = "Lots of Parameters"
});
var query = from p in db.EventsOnCloudData select p;
return query.ToList();
}
My Data Table:
[Table("cloudevents")]
public class EventsOnCloudData
{
[PrimaryKey, Identity]
public int Key { get; set; } // primary key / uid
[Column(Name = "Name"), NotNull]
public string Name { get; set; }
[Column(Name = "ErrorUrgency"), NotNull]
public string ErrorUrgency { get; set; }
[Column(Name = "EventCategory"), NotNull]
public string EventCategory { get; set; }
[Column(Name = "EventType"), NotNull]
public string EventType { get; set; }
[Column(Name = "JobId"), NotNull]
public int JobId { get; set; }
[Column(Name = "Time"), NotNull]
public DateTime Time { get; set; } //UTC
[Column(Name = "Parameters"), NotNull]
public string Parameters { get; set; } //JSON Parameters
}
LinqtoDB Data Connection Class:
public class EocIpcDB : LinqToDB.Data.DataConnection
{
public EocIpcDB() : base("eocipcdb") { }
public ITable<EventsOnCloudData> EventsOnCloudData => GetTable<EventsOnCloudData>();
}
Linq 2 DB settings Class:
public class EventsOnCloudSettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders => Enumerable.Empty<IDataProviderSettings>();
public string DefaultConfiguration => "SqlServer";
public string DefaultDataProvider => "SqlServer";
public IEnumerable<IConnectionStringSettings> ConnectionStrings
{
get
{
yield return
new ConnectionStringSettings
{
Name = "eocipcdb",
ProviderName = ProviderName.MySql,
ConnectionString = #"Server=.\;datasource=localhost;port=3306;database=eocipcdb;username=root;password=HPdfeHPdfe#1;"
};
}
}
}
internal class ConnectionStringSettings : IConnectionStringSettings
{
public string Name { get; set; }
public string ProviderName { get; set; }
public string ConnectionString { get; set; }
public bool IsGlobal => false;
}
This error generated by MySql.Data provider itself because you have server option set twice: Server=.\;datasource=localhost;. Server and Data Source are synonyms, alongside with host, data source, address, addr and network address
I am creating a user course project for learning MVC 4. In this project, when a user logs in they can see their courses and other details. A user can create or edit the courses. So I am displaying list of courses in dropdown list during create and edit. What I want is, when a user selects a course and it is added to his list of courses then that course should not be displayed in the dropdown list for that user. Some code for create is given below:
CourseController:
public ActionResult Create()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName");
ViewBag.UserId = usr.UserId;
ViewBag.FirstName = usr.FirstName;
}
return View();
}
//
// POST: /Course/Create
[HttpPost]
public ActionResult Create(UserCourse usercourse)
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
if (ModelState.IsValid)
{
db.UserCourses.Add(usercourse);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName", usercourse.CourseId);
ViewBag.UserId = usr.UserId;//from c in db.Users.Where(u => u.UserId == usercourse.UserId) select c;
ViewBag.FirstName = usr.FirstName;
return View();
}
return View(usercourse);
}
Create.cshtml:
<div class="editor-label">
#Html.DisplayNameFor(model => model.CourseId)
</div>
<div class="editor-field">
#Html.DropDownList("CourseId", String.Empty)
#Html.ValidationMessageFor(model => model.CourseId)
</div>
<p>
<input type="submit" value="Create" />
</p>
Model class for User:
public partial class User
{
public User()
{
this.UserCourses = new HashSet<UserCourse>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required(ErrorMessage = "Please Provide User Name", AllowEmptyStrings = false)]
public string UserName { get; set; }
[Required(ErrorMessage = "Please Provide Password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<UserCourse> UserCourses { get; set; }
}
Model class for Course:
public partial class Course
{
public Course()
{
this.UserCourses = new HashSet<UserCourse>();
}
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<UserCourse> UserCourses { get; set; }
}
Model class for UserCourse:
public partial class UserCourse
{
public int Id { get; set; }
public Nullable<int> UserId { get; set; }
public Nullable<int> CourseId { get; set; }
public virtual Course Course { get; set; }
public virtual User User { get; set; }
}
Please reply.
[EDITED]: Try it this way:
public ActionResult Create()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
var courses = db.Courses.Where(x=>!x.UserCourses.Any(y=>y.CourseId == x.CourseId && y.UserId == usr.UserId)).ToList();
ViewBag.CourseId = new SelectList(courses , "CourseId", "CourseName");
ViewBag.UserId = usr.UserId;
ViewBag.FirstName = usr.FirstName;
}
return View();
}
//
// POST: /Course/Create
[HttpPost]
public ActionResult Create(UserCourse usercourse)
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
if (ModelState.IsValid)
{
db.UserCourses.Add(usercourse);
db.SaveChanges();
return RedirectToAction("Index");
}
var courses = db.Courses.Where(x=>!x.UserCourses.Any(y=>y.CourseId == x.CourseId && y.UserId == usr.UserId)).ToList();
ViewBag.CourseId = new SelectList(courses, "CourseId", "CourseName", usercourse.CourseId);
ViewBag.UserId = usr.UserId;//from c in db.Users.Where(u => u.UserId == usercourse.UserId) select c;
ViewBag.FirstName = usr.FirstName;
return View();
}
return View(usercourse);
}
How to preserve the selected value after postback for that dropdownlist?
I have used two dropdown lists in my application. I need to search the gridview data based on the selected values of dropdownlist. The searched data is displayed in the pagedlist format. But when i move to next page of pagedlist, its displaying the whole grid view data rather than searched data. so any help will be appreciated.
My Model
namespace CCIOfficeServiceManagementSystem.Models
{
public class AirtelManagementModel
{
public long MobileAcNumber { get; set; }
public long AirtelNumber { get; set; }
public int OneTime { get; set; }
public float MonthlyCharges { get; set; }
public float CallCharges { get; set; }
public float ValueAddedServices { get; set; }
public float MobileInternetUsage { get; set; }
public float Roaming{ get; set; }
public float Discounts { get; set; }
public float Taxes { get; set; }
public float TotalCharges { get; set; }
public string WhoUploaded { get; set; }
public DateTime UploadedDate { get; set; }
public DateTime DateOfCreation { get; set; }
public int ImportDateId { get; set; }
public List<MonthListClass> MonthList
{
get;
set;
}
public List<clsYearOfDate> YearList
{
get;
set;
}
}
public class MonthListClass
{
public int MonthSelectedId { get; set; }
public string MonthName { get; set; }
}
public class clsYearOfDate
{
public int YearSelectedId { get; set; }
public string YearOfDate { get; set; }
}
}
My View
#using (Html.BeginForm("ViewDataOfDatabase", "AirtelManagement",FormMethod.Post))
{
<h3>Search by PhoneNumber:#Html.TextBox("SearchString",ViewBag.CurrentFilter as string)</h3>
<p><h3>Year:#Html.DropDownList("Yearitems", (IEnumerable<SelectListItem>)ViewBag.SelectList, "Select Year")</h3>
<h3>Month:#Html.DropDownList("MonthItems", (IEnumerable<SelectListItem>)ViewBag.SelectMonthList, "Select Month")</h3>
<h3>City: #Html.DropDownList("CityNames", (IEnumerable<SelectListItem>)ViewBag.CityList, "Select City")</h3></p>
<p><input type="submit" value="Search" /></p>
<script>
$(document).ready(function () {
$("#Yearitems").change(function () {
//debugger;
//alert($("#Yearitems>option:selected").attr("Value"));
$.ajax({
type: "Post",
url: '#Url.Action("GetMonths","AirtelManagement")',
data: { YearId: $("#Yearitems>option:selected").attr("Value") },
datatype: "Json",
success: function (data) {
//debugger;
$("#MonthItems").html("");
$.each(data, function (index, item) {
$("#MonthItems").append(new Option(item.MonthName, item.MonthSelectedId));
});
},
error: function () {
alert("Select Year");
}
});
});
});
</script>
My controller's action Method
public ActionResult ViewDataOfDatabase(string sortorder, string currentFilter, string searchString, int? page,FormCollection collection)
{
CCIRepository _repository = CCIRepository.CreateRepository();
AirtelManagementModel _Airtelmodel = new AirtelManagementModel();
IEnumerable<CityListClass> CityList = _repository.GetCities();
IEnumerable<SelectListItem> CityListItems = from c in CityList
select new SelectListItem()
{
Value = c.CityName.ToString(),
Text = c.CityName.ToString(),
Selected = c.CityName == Request["CityNames"],
};
ViewBag.CityList = CityListItems;
IEnumerable<clsYearOfDate> SelectList = GetYears();
//IEnumerable<MonthListClass> SelectMonthList = GetMonths(YearId);
IEnumerable<SelectListItem> Yearitems = (from v in SelectList
select new SelectListItem()
{
Value = v.YearSelectedId.ToString(),
Text = v.YearOfDate.ToString(),
Selected = v.YearOfDate == Request["Yearitems"],
});
ViewBag.SelectList = Yearitems;
int DateId=0;
string CityName = string.Empty;
try
{
int SelectedYear = Convert.ToInt16(collection["Yearitems"].ToString());
int SelectedMonth = Convert.ToInt16(collection["MonthItems"].ToString());
CityName = collection["CityNames"].ToString();
DateId = _repository.GetImportDateId(SelectedYear, SelectedMonth);
}
catch(NullReferenceException Ex)
{
}
//IEnumerable<SelectListItem> MonthItems = (from m in SelectMonthList
// select new SelectListItem()
// {
// Value = m.MonthSelectedId.ToString(),
// Text = m.MonthName,
// });
//ViewBag.SelectMonthList = MonthItems;
IEnumerable<SelectListItem> MonthItems = Enumerable.Empty<SelectListItem>();
ViewBag.SelectMonthList = MonthItems;
List<AirtelManagementModel> list = ViewDetails();
ViewBag.CurrentSort = sortorder;
ViewBag.PhoneSortParm = String.IsNullOrEmpty(sortorder) ? "Phone_desc" : "";
if (searchString != null )
{
page = 1;
}
else
{
searchString = currentFilter;
}
//if(searchString!=null)
//{
ViewBag.CurrentFilter = searchString;
var airteldetails = from _model in list
select _model;
if(!String.IsNullOrEmpty(searchString) && DateId!=0 && !String.IsNullOrEmpty(CityName))
{
airteldetails = _repository.FilterAirtelDetails(searchString, DateId, CityName);
int PageSize = 5;
int PageNumber = (page ?? 1);
return View(airteldetails.ToPagedList(PageNumber, PageSize));
}
//airteldetails=airteldetails.OrderByDescending(A=>A.AirtelNumber);
int pageSize = 5;
int pageNumber = (page ?? 1);
//return View(airteldetails.ToList());
return View(airteldetails.ToPagedList(pageNumber, pageSize));
//}
//if (list.Count > 0)
//{
// var airteldetails = from _model in list
// select _model;
// return View(airteldetails.ToPagedList(pageNumber,pageSize));
//}
//else
//{
// ModelState.AddModelError("Error", "No Data found in Database");
// return RedirectToAction("ImportExcelFile", "AirtelManagement");
//}
}
I am trying to put some distributed caching into play, I'm using this indeXus.Net Shared Cache .
It Requires that the object being cached is serializable, which it is here is the class object.
[Serializable]
public class Members
{
public Members()
{}
public Members(string aspnetusername, string aspnetpassword,
string emailaddr,string location)
: this(0,0,aspnetusername, aspnetpassword,emailaddr,DateTime.Now, location,
0,0,DateTime.Now,DateTime.Now,DateTime.Now,false)
{ }
public Members(Int64? row,int memberid, string aspnetusername, string aspnetpassword,
string emailaddr,DateTime datecreated, string location, int daimokugoal, int previewimageid,
DateTime lastdaimoku, DateTime lastnotifed, DateTime lastactivitydate, bool isactivated)
{
this.Row = row;
this.MemberID = memberid;
this.Aspnetusername = aspnetusername;
this.Aspnetpassword = aspnetpassword;
this.EmailAddr = emailaddr;
this.DateCreated = datecreated;
this.Location = location;
this.DaimokuGoal = daimokugoal;
this.PreviewImageID = previewimageid;
this.LastDaimoku = lastdaimoku;
this.LastNotefied = lastnotifed;
this.LastActivityDate = lastactivitydate;
this.IsActivated = this.IsActivated;
this.Details = new LazyList<MemberDetails>();
this.Blogs = new LazyList<MemberBlogs>();
this.Daimoku = new LazyList<MemberDaimoku>();
this.Determinations = new LazyList<MemberDeterminations>();
this.Encouragements = new LazyList<MemberEncouragements>();
this.Entries = new LazyList<MemberEntries>();
this.Friends = new LazyList<MemberFriends>();
this.Stats = new LazyList<MemberStats>();
}
public Int64? Row { get; set; }
public int MemberID { get; set; }
public string Aspnetusername { get; set; }
public string Aspnetpassword { get; set; }
public string EmailAddr { get; set; }
public DateTime DateCreated { get; set; }
public string Location { get; set; }
public int DaimokuGoal { get; set; }
public int PreviewImageID { get; set; }
public DateTime LastDaimoku { get; set; }
public DateTime LastNotefied { get; set; }
public DateTime LastActivityDate { get; set; }
public bool IsActivated { get; set; }
public LazyList<MemberDetails> Details { get; set; }
public LazyList<MemberBlogs> Blogs { get; set; }
public LazyList<MemberDaimoku> Daimoku { get; set; }
public LazyList<MemberDeterminations> Determinations { get; set; }
public LazyList<MemberEncouragements> Encouragements { get; set; }
public LazyList<MemberEntries> Entries { get; set; }
public LazyList<MemberFriends> Friends { get; set; }
public LazyList<MemberStats> Stats { get; set; }
}
The LINQtoSql is this that populates this class.
public IQueryable<Members> GetMemberInfo()
{
using (var t = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
var results = from m in _datacontext.ViewMembers
let details = GetMemberDetails(m.MemberID)
let determinations = GetMemberDeterminations(m.MemberID)
let daimoku = GetMemberDaimoku(m.MemberID)
let entries = GetMemberEntries(m.MemberID)
let blogs = GetMemberBlogs(m.MemberID)
let encouragements = GetMemberEncouragements(m.MemberID)
let friends = GetMemberFriends(m.MemberID)
let points = GetMemberStats(m.MemberID)
select new Members
{
Row = m.Row,
MemberID = m.MemberID,
Aspnetusername = m.Aspnetusername,
Aspnetpassword = m.Aspnetpassword,
EmailAddr = m.EmailAddr,
DateCreated = m.DateCreated,
Location = m.Location,
DaimokuGoal = m.DaimokuGoal,
PreviewImageID = m.PreviewImageID,
LastDaimoku = m.LastDaimoku.Value,
LastNotefied = m.LastNotefied.Value,
LastActivityDate = m.LastActivityDate.Value,
IsActivated = m.IsActivated,
Details = new LazyList<MemberDetails>(details),
Determinations = new LazyList<MemberDeterminations>(determinations),
Daimoku = new LazyList<MemberDaimoku>(daimoku),
Entries = new LazyList<MemberEntries>(entries),
Blogs = new LazyList<MemberBlogs>(blogs),
Encouragements = new LazyList<MemberEncouragements>(encouragements),
Friends = new LazyList<MemberFriends>(friends),
Stats = new LazyList<MemberStats>(points)
};
return results;
}
}
But for some reason I am getting this error
System.Runtime.Serialization.SerializationException: Type 'System.Data.Linq.DataQuery`1[[DaimokuBeta.MVC.Data.MemberDetails, DaimokuBeta.MVC.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
MemberDetails is serializable too..so not sure why it thinks it can't be serialized
Any ideas?
I believe that it's your LazyList implementation that cannot be serialized because the exception is telling us that the generic type DataQuery (from assembly System.Data.Linq) is not serializable. Is this type connected to your LazyList in any way?
If you are trying to cache the Members DTO (data transfer object) it's probably not a good idea to be applying lazy loading because it may only be executed in a very unpredictable moment.
Cache should usually be applied to data that has already been loaded/computed. Otherwise there may not be much point in using cache.