Adapting Linq Entity objects to Domain objects - asp.net-mvc

I have the following code which adapts linq entities to my Domain objects:
return from g in DBContext.Gigs
select new DO.Gig
{
ID = g.ID,
Name = g.Name,
Description = g.Description,
StartDate = g.Date,
EndDate = g.EndDate,
IsDeleted = g.IsDeleted,
Created = g.Created,
TicketPrice = g.TicketPrice
};
This works very nicely.
However I now want to populate a domain object Venue object and add it to the gig in the same statement. Heres my attempt....
return from g in DBContext.Gigs
join venue in DBContext.Venues on g.VenueID equals venue.ID
select new DO.Gig
{
ID = g.ID,
Name = g.Name,
Description = g.Description,
StartDate = g.Date,
EndDate = g.EndDate,
IsDeleted = g.IsDeleted,
Created = g.Created,
TicketPrice = g.TicketPrice,
Venue = from v in DBContext.Venues
where v.ID == g.VenueID
select new DO.Venue
{
ID = v.ID,
Name = v.Name,
Address = v.Address,
Telephone = v.Telephone,
URL = v.Website
}
};
However this doesnt compile!!!
Is it possible to adapt children objects using the "select new" approach?
What am I doing so very very wrong?

Your inner LINQ query returns several objects, not just one. You want to wrap it with a call like:
Venue = (from v in DBContext.Venues
where v.ID == g.VenueID
select new DO.Venue
{
ID = v.ID,
Name = v.Name,
Address = v.Address,
Telephone = v.Telephone,
URL = v.Website
}).SingleOrDefault()
Your choice of Single() vs. SingleOrDefault() vs. First() vs. FirstOrDefault() depends on what kind of query it is, but I'm guessing you want one of the first two. (The "OrDefault" variants return null if the query has no data; the others throw.)
I also agree with Mike that a join might be more in line with what you wanted, if there's a singular relationship involved.

Why are you doing a join and a sub select? You can just use the results of your join in the creation of a new Venue. Be aware that if there is not a one to one relationship between gigs and venues you could run into trouble.
Try this:
return from g in DBContext.Gigs
join venue in DBContext.Venues on g.VenueID equals venue.ID
select new DO.Gig { ID = g.ID, Name = g.Name, Description = g.Description,
StartDate = g.Date, EndDate = g.EndDate, IsDeleted = g.IsDeleted,
Created = g.Created, TicketPrice = g.TicketPrice,
Venue = new DO.Venue { ID = venue.ID, Name = venue.Name,
Address = venue.Address, Telephone = v.Telephone,
URL = v.Website }

Related

MVC - Linq to SQL JOINS

I have a controller that accepts a list of strings. THese strings essentially are IDs that a user selects on the view. I need to build the model based upon fields from to tables, hence the need for the join. The bellow code will not build as it claims the properties from the joined table do not exist. It only accepts table 1 values. Item.Well_No and Item.Well_Name throw the error. These are included in the "y" table that i joined to "x"..
[HttpPost]
public ActionResult buildSelectionTable(List<string> dta)
{
var a = from x in db._AGREEMENTS
join y in db.WELL_AGMT_XREF on x.AGMT_NUM equals y.AGMT_NUM
where dta.Contains(x.AGMT_NUM)
select x;
List<AgmtModel> model = new List<AgmtModel>();
foreach (var item in a)
{
model.Add(new AgmtModel { Agmt_Name = item.AGMT_NAME, Agmt_Num = item.AGMT_NUM, Agmt_Type = item.AGMT_TYPE_DESCR, Amnt_Status = item.AGMT_STAT_DESCR, Company = item.CO_NAME, DaysToExp = item.DaysToExp, Drs_Url = item.DRS_URL, Effective_Date = item.EFF_DT, Orig_Lessee = item.ORIG_LESSEE, Prop_Status = item.AGMT_PROP_STAT_DESCR, Expiration_Date = item.EXPR_DATE, Acreage = item.LGL_AREA, Extention_Expiration = item.EXTN_EXPR_DT, WellNo = item.WELL_NO, Well_Name = item.WELL_NAME });
}
return PartialView("_SelectionTable", model);
}
You are only selecting x in your query you need to also select y and reference it.
change select x to be select new { x, y}
and then
foreach (var item in a)
{
model.Add(new AgmtModel { Agmt_Name = item.y.AGMT_NAME, Agmt_Num = item.x.AGMT_NUM ... });
}
you need to insert .x or .y before you the field to determine the field names
alternatively you could actually put the constructor directly in the query
so instead of select x
select new AgmtModel { Agmt_Name = y.AGMT_NAME, etc...}
then you can just return PartialView("_SelectionTable", a.ToList())

Where on a List/Table in a Query

How can I do a where in a query on a list or table ?
To explain, I have a multiselect listbox where the user can select one or many values which are passed to my action. After that, I get all this values in a list and I want to do a Where on it like that :
List<string> CondCR = new List<string>();
foreach (var testCR in SubCR)
{
CondCR.Add(testCR);
}
ViewBag.CondCR = CondCR;
var query = (from i in items
where i.Field<String>("TIMING").Contains(GetTIMING) && i.Field<String>("CD_CR").Equals(CondCR)
select new Suivi{CD_CR = i.Field<String>("CD_CR"), CD_APPLI = i.Field<String>("CD_APPLI"), CD_TRT = i.Field<String>("CD_TRT"), LB_TRT = i.Field<String>("LB_TRT"),
PERIODE = i.Field<Int64>("PERIODE"), CD_JOB = i.Field<String>("CD_JOB"), LB_JOB = i.Field<String>("LB_JOB"), CD_TYP_TRT = i.Field<String>("CD_TYP_TRT"),
CD_TRT_SSIS = i.Field<String>("CD_TRT_SSIS"), DT_DEB = i.Field<DateTime>("DT_DEB"), DT_FIN = i.Field<DateTime>("DT_FIN"), DUREE = i.Field<String>("DUREE"),
TIMING = i.Field<String>("TIMING")
}).ToList();
return View(query);
SubCR contains the value that the user select in the list box, SubCR is of type string[].
I've tried to do a where on my list CondCR but it returns nothing and I don't know if it comes from my query or from an other thing.
Have you some suggestions ?
Okay, I've find the answer, I just had to do this in my query :
where CondCR.Contains(i.Field<String>("CD_CR").Trim()) && CondAppli.Contains(i.Field<String>("CD_APPLI").Trim())

Count books of user with Linq-To-Sql

I'm new in linq and i have a simple problem.
i must count how many books have user.
i know its easy but i cant do this.
//database
public List<UserViewModel> GetAllUsers()
{
var result = from u in databaseContext.User
select new UserViewModel
{
UserId = u.UserId,
LastName = u.LastName,
FirstName = u.FirstName,
BirthDate = u.BirthDate,
Email = u.Email,
Phone = u.Phone,
AddDate = u.AddDate,
ModifiedDate = u.ModifiedDate,
IsActive = u.IsActive,
};
return result.ToList();
}
how to do this?
In your model it seems that every Borrow has exactly one Book associated with it. If that is the case and the books cannot be taken more than once (which should be also correct) then all you need to do is:
int count = context.Users.First(x=>x.UserId = 1).Borrow.Count();
This way you can count all the Borrows of a given user supposing that they are all associated with a book.
If two borrows can have the same book than you should slightly rewrite this query to this:
int count = db.Borrow.Where(x => x.UserID== 1).Select(x => x.BookId).Distinct().Count();
This way you will get only the unique books borrowed from the user with id of 1.
To count only the unique books that are not returned use this:
int count = db.Borrow.Where(x => x.UserID== 1 && x.IsReturned == false).Select(x => x.BookId).Distinct().Count();

Error in linq join query in MVC 4

I am trying this query:
public ActionResult Index()
{
var topics = from t in db.Topics
join subs in db.Subjects on t.SubID equals subs.SubID
join mems in db.Members on t.MemberID equals mems.MemberID
select new ViewModel
{
TopicID = t.TopicID,
TDate = t.TDate,
Title = t.Title,
FileName = t.FileName,
Displays = t.Displays,
Description = t.Description,
SubName = subs.SubName,
FLName = mems.FLName
};
return View(topics);
}
But it causes the following Error:
The entity or complex type 'MySiteModel.ViewModel' cannot be constructed in a LINQ to Entities query.
I have an Entitity Class with above fields.
What is the problem? ????
Try convert it to List<> first.
var topics = (from t in db.Topics
join subs in db.Subjects on t.SubID equals subs.SubID
join mems in db.Members on t.MemberID equals mems.MemberID
select new ViewModel
{
TopicID = t.TopicID,
TDate = t.TDate,
Title = t.Title,
FileName = t.FileName,
Displays = t.Displays,
Description = t.Description,
SubName = subs.SubName,
FLName = mems.FLName
}).ToList();
Hope it helps

Insert into multiple database tables using Linq, ASP.NET MVC

I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B.
I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq.
What is the best approach ?
I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.
db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();
Int32 id = dbOject.Id;
//Rest of the code
Any way to elegantly do this?
Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.
Example...
Table A – Order
OrderId
OrderDate
Table B – Order Item
OrderItemId
OrderId
ItemId
Code (Using LINQ-to-SQL):
Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);
OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;
dataContext.InsertOnSubmit(item1);
dataContext.SubmitChanges();
hi i insert data into three table using this code
Product_Table AddProducttbl = new Product_Table();
Product_Company Companytbl = new Product_Company();
Product_Category Categorytbl = new Product_Category();
// genrate product id's
long Productid = (from p in Accountdc.Product_Tables
select p.Product_ID ).FirstOrDefault();
if (Productid == 0)
Productid++;
else
Productid = (from lng in Accountdc.Product_Tables
select lng.Product_ID ).Max() + 1;
try
{
AddProducttbl.Product_ID = Productid;
AddProducttbl.Product_Name = Request.Form["ProductName"];
AddProducttbl.Reorder_Label = Request.Form["ReorderLevel"];
AddProducttbl.Unit = Convert.ToDecimal(Request.Form["Unit"]);
AddProducttbl.Selling_Price = Convert.ToDecimal(Request.Form["Selling_Price"]);
AddProducttbl.MRP = Convert.ToDecimal(Request.Form["MRP"]);
// Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl );
// genrate category id's
long Companyid = (from c in Accountdc.Product_Companies
select c.Product_Company_ID).FirstOrDefault();
if (Companyid == 0)
Companyid++;
else
Companyid = (from Ct in Accountdc.Product_Companies
select Ct.Product_Company_ID).Max() + 1;
Companytbl.Product_Company_ID = Companyid;
Companytbl.Product_Company_Name = Request.Form["Company"];
AddProducttbl.Product_Company = Companytbl;
//Genrate Category id's
long Categoryid = (from ct in Accountdc.Product_Categories
select ct.Product_Category_ID).FirstOrDefault();
if (Categoryid == 0)
Categoryid++;
else
Categoryid = (from Ct in Accountdc.Product_Categories
select Ct.Product_Category_ID).Max() + 1;
Categorytbl.Product_Category_ID = Categoryid;
Categorytbl.Product_Category_Name = Request.Form["Category"];
AddProducttbl.Product_Category = Categorytbl;
Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl);
Accountdc.SubmitChanges();
}
catch
{
ViewData["submit Error"] = "No Product Submit";
}

Resources