I have this linq query where i want to remove all the duplicates based on the column MAILADR (but keep the other columns):
Dim dataObject = (From a In db.TABLE1 Select New With {
.ID = a.BENUTZERNR,
.MAILADR = a.EMAIL,
.BENUTZERGRP = a.USRGRP
}) _
.Union(
(From b In db.TABLE12 Select New With {
.ID = b.ID,
.MAILADR = b.MAILADR,
.BENUTZERGRP = b.BENUTZERGRP
}) _
)
You can provide a comparison method (IEqualityComparer) on the overloaded Union method.
http://msdn.microsoft.com/en-us/library/bb358407.aspx
I ended up using the GroupByoperator:
dataObject = dataObject.GroupBy(Function(c) c.MAILADR).Select(Function(group) group.First())
Related
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())
I'm fairly new at MVC and linq and viewmodels in particular. I managed to get a create and index views to work. The "insert" wasn't as hard as the "list".
I have this linq query:
public ActionResult Index()
{
List<BlendElVM> BEVM = new List<BlendElVM>();
var list = (from Blend in db.blends
join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
select new
{
Blend.ID, Blend.Title, Blend.TransDt, BlendEl.Comment
}).ToList();
foreach (var item in list)
{
BlendElVM o = new BlendElVM(); // ViewModel
o.Comment = item.Comment;
o.Title = item.Title;
o.TransDt = item.TransDt;
o.ID = item.ID;
BEVM.Add(o);
}
return View(BEVM);
}
What I'm not sure about is the "foreach" section. When I'm running in debug, the "list" shows up fine, but if I comment out the "foreach" I get an error - ie not expecting the model. What does the foreach do? It has to do with the database, but I don't understand the where it is using the "o" and setting the columns. I thought it would all be in one linq query. Is it possible to combine the two and eliminate the "foreach"?
var BEVM = (from blend in db.blends
join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
select new BlendELVM
{
ID = blend.ID,
Title = blend.Title,
TransDT = blend.TransDt,
comment = blendEl.Comment
}).ToList();
I believe that the foreach is needed in order to read every element in the object so in this case you have:
BlendElVM o = new BlendElVM();
So you're creating and object named " o " of the type BlendELVM and this object contains all the attributes that you declared before which are: ID, Title, TransDT, etc
When you put:
foreach (var item in list)
{
BlendElVM o = new BlendElVM(); // ViewModel
o.Comment = item.Comment;
o.Title = item.Title;
o.TransDt = item.TransDt;
o.ID = item.ID;
BEVM.Add(o);
}
You're assigning to the new object o the item that you're reading in the list and in the end adding it to the BVEM list and answering if you can combine them i will say no because at first you're declaring the query and then you're reading the items on the list and assining them to the BEVM list
I feel like I must me missing something very simple. It's a very simple task, all I want to do is get something like:
SELECT * FROM lookup_items
JOIN lookup ON lookup_items.lookup_id = lookup.id
This returns all the columns for all the joined tables, in regular SQL. Here's my attempt in zf2:
$select = new Select();
$select->from('lookup_items');
$select->join('lookup', 'lookup_items.lookup_id = lookup.id');
The result set only includes the columns in 'lookup_items'. I've tried various ways to get the 'lookup' columns, including:
$select->columns(array('lookup_items.*', 'lookup.*'));
But they all just blow up. Surely there's a way to do this, and it's just so simple I'm missing it completely.
I thought a simple example would be avoid confusion, but here's more code:
class LookupItemsTable extends AbstractTableGateway
{
public function getList($resource)
{
$system_name = str_replace('*', '%', strtoupper($resource));
$joinTable = 'lookup';
$select = new Select();
$select->from($this->table);
$select->join($joinTable, "{$this->table}.lookup_id = {$joinTable}.id");
$where = array();
$where[] = "{$this->table}.enabled is true";
$where[] = "{$joinTable}.enabled is true";
$where[] = "UPPER({$joinTable}.system_name) ilike '{$system_name}'";
$select->where($where);
$sort[] = 'sort_order ASC';
$sort[] = 'value ASC';
$select->order($sort);
$rowset = $this->selectWith($select);
return $rowset;
}
}
Where:
$resource = $this->params()->fromRoute('resource', 'BUSINESS');
And $this->table is 'lookup_items'. Really all I want to do is get columns from both joined tables. I guess there's a zf2 way to just make a straight SQL statement without all the OO falderal, so I could just force it that way. But I'd rather work within the framework as much as possible.
Just change this line
$select->join('lookup', 'lookup_items.lookup_id = lookup.id');
to
$select->join('lookup', 'lookup_items.lookup_id = lookup.id', array('lookupcol1', 'lookupcol2');
Raj answer is the best one but it only works if you don't forget to add these fiels in your LookupItems model.
class LookupItems
{
// Your lookup_items fields here...
...
// And the added lookup fields here, the ones you add in the array
public $lookupcol1;
public $lookupcol2;
And in the exchangeArray method :
public function exchangeArray($data)
{
// .... your fields, and the new ones
$this->lookupcol1 = (! empty($data['lookupcol1'])) ? $data['lookupcol1'] : null;
$this->lookupcol2 = (! empty($data['lookupcol2'])) ? $data['lookupcol2'] : null;
}
I figured it out.
Added this:
$select->columns(array('*'));
And then this near the end:
$sql = new Sql($this->adapter);
$statement = $sql->prepareStatementForSqlObject($select);
$rowset = $statement->execute();
This returns the expected result, with the caveat that now my rows are returned as associative arrays instead of objects.
This is how you can create queries with join in zf2.
$resultSet = $this->select(function (Select $select) {
// omit the table name
//$select->from('foo');
$select->join('users', "users.id foo.createdby", 'firstname', '');
$select->order('id ASC');
// echo $select->getSqlString();// to print your query
});
$entities = array();
foreach ($resultSet as $row) {
$entity = new Entity\Foo();
$entity->setId($row->id)
->setFullname($row->fullname)
->setCaseid($row->caseid)
->setTestimonial($row->testimonial)
->setSortorder($row->sortorder)
->setActive($row->active)
->setCreated($row->created)
->setModified($row->modified)
->setFirstname($row->firstname)
->setCreatedby($row->createdby);
$entities[] = $entity;
}
return $entities;
I am trying to create a multiple choice questionnaire that is table-driven. There is a Question that has child Choices within each question.
When I iterate the listOfQuestions, the first SQL is executed. I thought by "including" Choices that this would prevent a secondary lookup from occuring when I loop though the Choices for the current Question, but it did not.
Why?
var listOfQuestions = (from q in journeyEastContext.Questions.Include("Choices")
orderby q.QuestionId
select new
{
Question = q,
Choices = q.Choices.OrderBy(c => c.Sequence)
});
foreach (var questionGroup in listOfQuestions)
{
Question question = questionGroup.Question;
Literal paragraph = new Literal
{
Text = "<P/>"
};
this.QuestionPanel.Controls.Add(paragraph);
Label QuestionLabel = new Label
{
Text = question.Text
};
this.QuestionPanel.Controls.Add(QuestionLabel);
//var sortedChoices = from choices in question.Choices
// orderby choices.Sequence
// select choices;
foreach (Choice choice in question.Choices)
{
Literal carrageReturn = new Literal
{
Text = "<BR/>"
};
this.QuestionPanel.Controls.Add(carrageReturn);
RadioButton choiceRadioButton = new RadioButton()
{
ID = String.Format("{0},{1}", question.QuestionId, choice.ChoiceId),
Text = choice.Text,
GroupName = question.QuestionId.ToString()
};
this.QuestionPanel.Controls.Add(choiceRadioButton);
}
}
It is because of the projection being part of the query.
select new
{
Question = q,
Choices = q.Choices.OrderBy(c => c.Sequence)
});
There are a few ways to approach the solution to this, the simplest would be
var quesitonsList = (from q in journeyEastContext.Questions.Include("Choices")
orderby q.QuestionId).ToList();
var listOfQuestions = from q in questionsList
Select new
{
Question = q,
Choices = q.Choices.OrderBy(c => c.Sequence)
});
This would tell EF to execute the first query (with the Choices property eagerly loaded) and then let you run through your iteration without having extra queries fired off.
.Include and .Select do not mix because of the type of query being generated in T-SQL. Basically projections use inner select statements and eagerly loaded properties use denormalization and joins to flatten the record set.
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";
}