Edit on Model - complex types not updated properly - asp.net-mvc-3

I have this two objects - Magazine and Author (M-M relationship):
public partial class MAGAZINE
{
public MAGAZINE()
{
this.AUTHORs = new HashSet<AUTHOR>();
}
public long REF_ID { get; set; }
public string NOTES { get; set; }
public string TITLE { get; set; }
public virtual REFERENCE REFERENCE { get; set; }
public virtual ICollection<AUTHOR> AUTHORs { get; set; }
}
public partial class AUTHOR
{
public AUTHOR()
{
this.MAGAZINEs = new HashSet<MAGAZINE>();
}
public long AUTHOR_ID { get; set; }
public string FULL_NAME { get; set; }
public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
}
}
My problem is that I can't seem to update the number of authors against a magazine e.g. if I have 1 author called "Smith, P." stored already against a magazine, I can add another called "Jones, D.", but after the post back to the Edit controller the number of authors still shows 1 - i.e. "Smith, P.H".
Please not that I have successfully model bound the number of authors back to the parent entity (Magazine), it uses a custom model binder to retrieve the authors and bind to the Magazine (I think), but it still doesn't seem to update properly.
My code for updating the model is straight forward - and shows the variable values both before and after:
public ActionResult Edit(long id)
{
MAGAZINE magazine = db.MAGAZINEs.Find(id);
return View(magazine);
}
and here are the variables pre-editing/updating -
[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
{
if (ModelState.IsValid)
{
db.Entry(magazine).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(magazine);
}
...and here are the variables after a new author has been added...
I am getting suspicious that the author entity is showing, post edit that it is not bound to any magazine and I am guessing this is why it is not being updated back to the magazine entity - but it is perplexing as I am effectively dealing with the same magazine entity - I guess it may be something to do with the custom model binder for the author.
Can anyone help on this matter?
For completeness - I have included my AuthorModelBinder class too -
public class AuthorModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null)
{
// We have specified asterisk (*) as a token delimiter. So
// the ids will be separated by *. For example "2*3*5"
var ids = values.AttemptedValue.Split('*');
List<int> validIds = new List<int>();
foreach (string id in ids)
{
int successInt;
if (int.TryParse(id, out successInt))
{
validIds.Add(successInt);
}
else
{
//Make a new author
AUTHOR author = new AUTHOR();
author.FULL_NAME = id.Replace("\'", "").Trim();
using (RefmanEntities db = new RefmanEntities())
{
db.AUTHORs.Add(author);
db.SaveChanges();
validIds.Add((int)author.AUTHOR_ID);
}
}
}
//Now that we have the selected ids we could fetch the corresponding
//authors from our datasource
var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
{
AUTHOR_ID = x.Key,
FULL_NAME = x.Value
}).ToList();
return authors;
}
return Enumerable.Empty<AUTHOR>();
}
}

I faced a very similar scenario when I developed my blog using MVC/Nhibernate and the entities are Post and Tag.
I too had an edit action something like this,
public ActionResult Edit(Post post)
{
if (ModelState.IsValid)
{
repo.EditPost(post);
...
}
...
}
But unlike you I've created a custom model binder for the Post not Tag. In the custom PostModelBinder I'm doing pretty much samething what you are doing there (but I'm not creating new Tags as you are doing for Authors). Basically I created a new Post instance populating all it's properties from the POSTed form and getting all the Tags for the ids from the database. Note that, I only fetched the Tags from the database not the Post.
I may suggest you to create a ModelBinder for the Magazine and check it out. Also it's better to use repository pattern instead of directly making the calls from controllers.
UPDATE:
Here is the complete source code of the Post model binder
namespace PrideParrot.Web.Controllers.ModelBinders
{
[ValidateInput(false)]
public class PostBinder : IModelBinder
{
private IRepository repo;
public PostBinder(IRepository repo)
{
this.repo = repo;
}
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
// retrieving the posted values.
string oper = request.Form.Get("oper"),
idStr = request.Form.Get("Id"),
heading = request.Form.Get("Heading"),
description = request.Form.Get("Description"),
tagsStr = request.Form.Get("Tags"),
postTypeIdStr = request.Form.Get("PostType"),
postedDateStr = request.Form.Get("PostedDate"),
isPublishedStr = request.Form.Get("Published"),
fileName = request.Form.Get("FileName"),
serialNoStr = request.Form.Get("SerialNo"),
metaTags = request.Form.Get("MetaTags"),
metaDescription = request.Form.Get("MetaDescription"),
themeIdStr = request.Form.Get("Theme");
// initializing to default values.
int id = 0, serialNo = 0;
DateTime postedDate = DateTime.UtcNow;
DateTime? modifiedDate = DateTime.UtcNow;
postedDate.AddMilliseconds(-postedDate.Millisecond);
modifiedDate.Value.AddMilliseconds(-modifiedDate.Value.Millisecond);
/*if operation is not specified throw exception.
operation should be either'add' or 'edit'*/
if (string.IsNullOrEmpty(oper))
throw new Exception("Operation not specified");
// if there is no 'id' in edit operation add error to model.
if (string.IsNullOrEmpty(idStr) || idStr.Equals("_empty"))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("Id", "Id is empty");
}
else
id = int.Parse(idStr);
// check if heading is not empty.
if (string.IsNullOrEmpty(heading))
bindingContext.ModelState.AddModelError("Heading", "Heading: Field is required");
else if (heading.Length > 500)
bindingContext.ModelState.AddModelError("HeadingLength", "Heading: Length should not be greater than 500 characters");
// check if description is not empty.
if (string.IsNullOrEmpty(description))
bindingContext.ModelState.AddModelError("Description", "Description: Field is required");
// check if tags is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("Tags", "Tags: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("TagsLength", "Tags: Length should not be greater than 500 characters");
// check if metadescription is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Length should not be greater than 500 characters");
// check if file name is not empty.
if (string.IsNullOrEmpty(fileName))
bindingContext.ModelState.AddModelError("FileName", "File Name: Field is required");
else if (fileName.Length > 50)
bindingContext.ModelState.AddModelError("FileNameLength", "FileName: Length should not be greater than 50 characters");
bool isPublished = !string.IsNullOrEmpty(isPublishedStr) ? Convert.ToBoolean(isPublishedStr.ToString()) : false;
//** TAGS
var tags = new List<PostTag>();
var tagIds = tagsStr.Split(',');
foreach (var tagId in tagIds)
{
tags.Add(repo.PostTag(int.Parse(tagId)));
}
if(tags.Count == 0)
bindingContext.ModelState.AddModelError("Tags", "Tags: The Post should have atleast one tag");
// retrieving the post type from repository.
int postTypeId = !string.IsNullOrEmpty(postTypeIdStr) ? int.Parse(postTypeIdStr) : 0;
var postType = repo.PostType(postTypeId);
if (postType == null)
bindingContext.ModelState.AddModelError("PostType", "Post Type is null");
Theme theme = null;
if (!string.IsNullOrEmpty(themeIdStr))
theme = repo.Theme(int.Parse(themeIdStr));
// serial no
if (oper.Equals("edit"))
{
if (string.IsNullOrEmpty(serialNoStr))
bindingContext.ModelState.AddModelError("SerialNo", "Serial No is empty");
else
serialNo = int.Parse(serialNoStr);
}
else
{
serialNo = repo.TotalPosts(false) + 1;
}
// check if commented date is not empty in edit.
if (string.IsNullOrEmpty(postedDateStr))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("PostedDate", "Posted Date is empty");
}
else
postedDate = Convert.ToDateTime(postedDateStr.ToString());
// CREATE NEW POST INSTANCE
return new Post
{
Id = id,
Heading = heading,
Description = description,
MetaTags = metaTags,
MetaDescription = metaDescription,
Tags = tags,
PostType = postType,
PostedDate = postedDate,
ModifiedDate = oper.Equals("edit") ? modifiedDate : null,
Published = isPublished,
FileName = fileName,
SerialNo = serialNo,
Theme = theme
};
}
#endregion
}
}

This line db.Entry(magazine).State = EntityState.Modified; only tells EF that magazine entity has changed. It says nothing about relations. If you call Attach all entities in object graph are attached in Unchanged state and you must handle each of them separately. What is even worse in case of many-to-many relation you must also handle relation itself (and changing state of relation in DbContext API is not possible).
I spent a lot of time with this problem and design in disconnected app. And there are three general approaches:
You will send additional information with your entities to find what has changed and what has been deleted (yes you need to track deleted items or relations as well). Then you will manually set state of every entity and relation in object graph.
You will just use data you have at the moment but instead of attaching them to the context you will load current magazine and every author you need and reconstruct those changes on those loaded entities.
You will not do this at all and instead use lightweight AJAX calls to add or remove every single author. I found this common for many complex UIs.

Related

The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query

As you can see, I got this error when I built Data Gird using Kendo UI. Does anybody could point out where I'm wrong in my code below.
private IEnumerable<Product> GetSubProduct()
{
var context = new AdvenDBEntities();
var subcate = context.Products.Select(p => new Product
{
ProductID = p.ProductID,
Name = p.Name,
Color = p.Color,
ListPrice = p.ListPrice,
}).ToList();
return subcate;
}
Error:
The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query.
Thank you so much for your time!
Since Product is an entity of model, you are creating new object of this entity while selecting the records, which is NOT good idea, I am NOT sure how model will handle this kind of behaviour that is why it is preventing you to do so, (I guess). Anyway you can change the code to this,
private IEnumerable<Product> GetSubProduct()
{
var context = new AdvenDBEntities();
var subcate = context.Products.ToList();
return subcate;
}
BTW your function name indicating that you are missing a Where clause.
Also you can create some custom DTO class and use it instead.
E.g.
class ProductDTO
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public decimal ListPrice { get; set; }
}
private IEnumerable<ProductDTO> GetSubProduct()
{
var context = new AdvenDBEntities();
var subcate = context.Products.Select(p => new ProductDTO
{
ProductID = p.ProductID,
Name = p.Name,
Color = p.Color,
ListPrice = p.ListPrice,
}).ToList();
return subcate;
}
The first bad smell code I can point out for you. DBContext implements IDisposable so you are responsible for calling Dispose on it. In all, but one case in here, using block
You must build query to get all the product and then extract from it.
private IEnumerable<Product> GetSubProduct()
{
using (var context = new AdvenDBEntities())
{
// Get all constructed type product and then select from it
var subcate = context.Products
.ToList()
.Select(p => new Product
{
ProductID = p.ProductID,
Name = p.Name,
Color = p.Color,
ListPrice = p.ListPrice,
});
return subcate;
}
}

Unable to cast object of type WhereSelectListIterator

I have been attempting to figure out why a Linq query that returns a list of U.S. States formatted for a drop down list will not cast to a List when the code returns to the calling method. The error that I get is:
Unable to cast object of type 'WhereSelectListIterator'2[StateListing.States,<>f__AnonymousTypea'2[System.String,System.String]]' to type 'System.Collections.Generic.List`1[StateListing.States]'
The namespace StateListing from the error, is a dll library that has a class called States returning an IEnumerable List of states shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StateListing
{
public class States
{
public string StateAbbriviation { get; set; }
public int StateID { get; set; }
public string StateName { get; set; }
static int cnt = 0;
public static IEnumerable<States> GetStates()
{
return new List<States>
{
new States
{
StateAbbriviation = "AL",
StateID=cnt++,
StateName = "Alabama"
},
new States
{
StateAbbriviation = "AL",
StateID=cnt++,
StateName = "Alaska"
}
//Continued on with the rest of states
}.AsQueryable();
}
}
}
In my control I make a call to GetStates that returns a List of States from the class library above.
[HttpPost]
public JsonResult GetStateOptions()
{
try
{
//Return a list of options for dropdown list
var states = propertyRepository.GetStates();
return Json(new { Result = "OK", options = states });
}
In the property repository class I have two methods one to get the StateList from the library, and another to format the listing of states for a drop down list in my view.
public List<States> GetStateList()
{
var items = (from s in States.GetStates()
select s).ToList();
return items;
}
List<States> IPropertyRepository.GetStates()
{
try
{
List<States> RawStates = GetStateList();
var stateList = RawStates.Select(c => new { DisplayText = c.StateName, Value = c.StateID.ToString() });
return (List<States>)stateList; //<=== Error
}
The error occurs when the code reaches the return within the GetStates method.
Any help with this casting problem explaining what I'm doing wrong would be appreciated.
This is the problem:
var stateList = RawStates.Select(c => new { DisplayText = c.StateName,
Value = c.StateID.ToString() });
return (List<States>)stateList;
Two issues:
Select doesn't return a List<T>
You're not= selecting States objects; you're selecting an anonymous type
The first is fixable using ToList(); the second is fixable either by changing your Select call or by changing your method's return type. It's not really clear what you really want to return, given that States doesn't have a DisplayText or Value property.
I would expect a method of GetStates to return the states - in which case you've already got GetStatesList() which presumably does what you want already.
Basically, you need to think about the type you really want to return, and make both your method return type and the method body match that.
You are projecting your LINQ query to an anonymmous object and not to a State list which obviously cannot work. The 2 types are incompatible. So start by modifying your repository layer and get rid of the GetStateList method:
public class PropertyRepository: IPropertyRepository
{
public List<States> GetStates()
{
return States.GetStates().ToList();
}
}
and then project to the desired structure in your controller:
[HttpPost]
public JsonResult GetStateOptions()
{
var states = propertyRepository.GetStateList();
var options = states.Select(x => new
{
DisplayText = c.StateName,
Value = c.StateID.ToString()
}).ToList();
return Json(new { Result = "OK", options = states });
}

Trouble filling and using MultiSelectList/ListBoxFor in ASP.NET MVC 3

I'm trying to adapt the answers for filling a ListBoxFor that has preselected values that I've found here on SO and am having some trouble with the adaptation.
This is one of the questions I've been referring to: here
Here is my class that defines a list object
public class SelectListDTO {
public int ID { get; set; }
public string Name { get; set; }
}
I have a method on a class that fills a List of SelectListDTO items. The CheckRefresh checks to see if the cache is expired, if so it refills the cache. So this method gets my list:
private List<SelectListDTO> GetSelectList() {
CheckRefresh();
var lst = new List<SelectListDTO>(_cache.Count + 1);
_cache.ForEach(item => lst.Add(new SelectListDTO { ID = item.ID, Name = item.Name }));
return lst;
}
My Model is define with these Properties/Methods:
public class MyModel {
[Required]
[Display(Name = "Program Type")]
[Min(1, ErrorMessage = "Please select a Program Type")]
public int[] SelectedProgramTypes { get; set; }
public MultiSelectList ProgramTypes { get; set; }
public MyModel() {
PopulateProgramTypeList();
}
private void PopulateProgramTypeList() {
// Get all available list items
var programTypes = ProgramTypeService.Instance.GetSelectList;
// how to fill multiselectlist with my List<SelectListDTO> items;
ProgramTypes = new MultiSelectList(??)
}
}
1st part of question is from above here^ How to fill the MultiSlectList with my List of SelectListDTO objects
Also in my controller action I am getting the saved items from the DB and will need to pass them to the model as SelectedProgramTypes. This is currently in my action:
public ActionResult Edit(int? id) {
// Code here to validate id and that user is associated with id
lenderProduct = new LenderProduct(id);
var model = BuildModel(lenderProduct); // returns instance or MyModel
var selectedProgramTypes = lenderProduct.ProgramTypes;
foreach (var item in selectedProgramTypes) {
/// How to fill the Model.SelectedProgramTypes array
}
return View(model);
}
2nd part of question is how to get the currently selected items that I read from the DB into the array that can be used by the MultiSelectList in the Model
I feel like I'm this close but am missing some pattern or hopefully just the correct syntax into getting this to work in this way as opposed to the ways I've seen posted here.
I haven't made it to the View yet but from what I've seen that is just as easy as filling a normal DropDownList.
1st part of question is from above here^ How to fill the
MultiSlectList with my List of SelectListDTO objects
ProgramTypes = new MultiSelectList(programTypes.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
}));
2nd part of question is how to get the currently selected items that I
read from the DB into the array that can be used by the
MultiSelectList in the Model
It's not clear how your LenderProduct class looks like but assuming the ProgramTypes property is just an array of integers you could directly assign it to your view model:
public ActionResult Edit(int? id)
{
// Code here to validate id and that user is associated with id
var lenderProduct = new LenderProduct(id);
var model = BuildModel(lenderProduct); // returns instance or MyModel
model.SelectedProgramTypes = lenderProduct.ProgramTypes;
return View(model);
}
and if it is an array of some complex object you could select the corresponding property that contains the id:
public ActionResult Edit(int? id)
{
// Code here to validate id and that user is associated with id
var lenderProduct = new LenderProduct(id);
var model = BuildModel(lenderProduct); // returns instance or MyModel
model.SelectedProgramTypes = lenderProduct.ProgramTypes.Select(x => x.ID).ToArray();
return View(model);
}

When updating Marking entity datetime property unchanged

I have this entity service in my domain model with two datetime type properties entrydate and updatedon.
When user in edit view make any changes and submit form back I want entrydate property of the postedback/modified object to be marked as unchanged so entrydate can't be overwritten when performing updates.
public class Service
{
public int ServiceID
{
get;
set;
}
[Required(ErrorMessage="Please enter Name")]
public string Name
{
get;
set;
}
[Required(ErrorMessage="Please enter the duration for the service")]
public short Duration
{
get;
set;
}
[DataType(DataType.Date)]
public DateTime EntryDate
{
get;
set;
}
[DataType(DataType.Date)]
public DateTime UpdatedOn
{
get;
set;
}
public decimal Cost
{
get; set;
}
}
Repository method that is persisting changes into db is as follows:
public void InsertOrUpdate(Service service)
{
if (service.ServiceID == default(int)) {
// New entity
context.Services.Add(service);
} else {
// Existing entity
context.Entry(service).State = EntityState.Modified;
}
}
You can reload the original entity from the database:
else {
// Existing entity
var serviceInDb = context.Services.Find(service.ServiceID);
service.EntryDate = serviceInDb.EntryDate;
context.Entry(serviceInDb).CurrentValues.SetValues(service);
}
When you call SaveChanges later an UPDATE statement only for properties which have really changed will be sent to the database (has also benefits for other unchanged properties).
Or just reload the EntryDate:
else {
// Existing entity
var entryDateInDb = context.Services
.Select(s => s.EntryDate)
.Single(s => s.ServiceID == service.ServiceID);
service.EntryDate = entryDateInDb;
context.Entry(service).State = EntityState.Modified;
}
Another working but ugly approach is this:
context.Services.Attach(service); // thanks to user202448, see comments
context.Entry(service).Property(s => s.Name).IsModified = true;
context.Entry(service).Property(s => s.Duration).IsModified = true;
context.Entry(service).Property(s => s.UpdatedOn).IsModified = true;
context.Entry(service).Property(s => s.Cost).IsModified = true;
So, don't set the EntryDate property to modified but all the other properties one by one.
The approach which comes into mind ...
context.Entry(service).State = EntityState.Modified;
context.Entry(service).Property(s => s.EntryDate).IsModified = false;
... unfortunately doesn't work because setting back a property to not-modified which is already marked as Modified is not supported and will throw an exception.

Returning LINQ to Entities Query Result as JSON string

I'm attempting to construct a web service that allows for RESTful requests to return LINQ to Entities data as JSON string data. I have no problem executing a call to the database that returns one specific object:
public Product GetTicket(string s)
{
int id = Convert.ToInt32(s);
MWAEntities context = new MWAEntities();
var ticketEntity = (from p
in context.HD_TicketCurrentStatus
where p.Ticket_ID == id
select p).FirstOrDefault();
if (ticketEntity != null)
return TranslateTicketEntityToTicket(ticketEntity);
else
throw new Exception("Invalid Ticket ID");
/**
Product product = new Product();
product.TicketId = 1;
product.TicketDescription = "MyTest";
product.TicketOperator = "Chad Cross";
product.TicketStatus = "Work in Progress";
return product;
*/
}
private Product TranslateTicketEntityToTicket(
HD_TicketCurrentStatus ticketEntity)
{
Product ticket = new Product();
ticket.TicketId = ticketEntity.Ticket_ID;
ticket.TicketDescription = ticketEntity.F_PrivateMessage;
ticket.TicketStatus = ticketEntity.L_Status;
ticket.TicketOperator = ticketEntity.L_Technician;
return ticket;
}
Using curl, I get json data:
curl http://192.168.210.129:1111/ProductService/ticket/2
{"TicketDescription":"Firewall seems to be blocking her connection to www.rskco.com","TicketId":2,"TicketOperator":"Jeff","TicketStatus":"Completed"}
That being said, I have no idea how to get a string of JSON objects using the following query:
public List<MyTicket> GetMyTickets(string userId)
{
MWAEntities context = new MWAEntities();
/**
* List of statuses that I consider to be "open"
* */
string[] statusOpen = new string[] { "Work in Progress", "Assigned", "Unassigned" };
/**
* List of tickets with my userID
* */
var tickets = (from p
in context.HD_TicketCurrentStatus
where statusOpen.Contains(p.L_Status) & p.L_Technician == userId
select new MyTicket(p.Ticket_ID, p.Ticket_CrtdUser, p.F_PrivateMessage, p.Ticket_CrtdDate, p.L_Status));
return ???;
}
MyTicket is a type defined as follows:
[DataContract]
public class MyTicket
{
public MyTicket(int ticketId, string TicketCreator, string FirstPrivateMessage, DateTime TicketCreatedDate, string Status)
{
this.TicketId = ticketId;
this.TicketCreator = TicketCreator;
this.FirstPrivateMessage = FirstPrivateMessage;
this.TicketCreatedDate = TicketCreatedDate;
this.Status = Status;
}
[DataMember]
public int TicketId { get; set; }
[DataMember]
public string TicketCreator { get; set; }
[DataMember]
public string FirstPrivateMessage { get; set; }
[DataMember]
public DateTime TicketCreatedDate { get; set; }
[DataMember]
public string Status { get; set; }
//p.Ticket_CrtdUser, p.Ticket_CrtdDate, p.Ticket_ID, p.F_PrivateMessage
}
I would just like to get a list of JSON strings as output in order to parse using JS. I've tried using a foreach loop to parse "var" into a List of MyTicket objects, calling .ToList()), etc., to no avail.
I cannot change the backend (SQL 2005/2008), but I'm trying to use a standard HTML/JS client to consume a .NET 4.0 web service. Any help would be greatly appreciated. I've spent literally days searching and reading books (especially on O'Reilly's Safari site) and I have not found a reasonable solution :(.
use Json.NET: http://james.newtonking.com/pages/json-net.aspx
using Newtonsoft.Json;
var serializer = new JsonSerializer();
serializer.Serialize(Response.Output, tickets); // per your example
EDIT: Argh, the above is if you want to handle the serialization yourself.
In your example, change the return of the method from List to Ticket[] and do
return tickets.ToArray();
I wanted to add that I eventually got help to solve this. I'm not using business entities even though I'm using the Entity Framework. This may not be a wise decision, but I'm increasingly confused with Linq2SQL and Linq2EF. Here is the the code that made the above work:
public List<MyTicket> GetMyTickets(string userId)
{
MWAEntities context = new MWAEntities();
/**
* List of statuses that I consider to be "open"
* */
string[] statusOpen = new string[] { "Work in Progress", "Created"};
var tickets = (from p
in context.HD_TicketCurrentStatus
where statusOpen.Contains(p.L_Status) & p.L_Technician == userId
select new MyTicket{
TicketId = p.Ticket_ID,
TicketCreatedDate = p.Ticket_CrtdDate,
FirstPrivateMessage = p.F_PrivateMessage,
Status = p.L_Status,
TicketCreator = p.Ticket_CrtdUser
});
return tickets.ToList();
}

Resources