For example :
<asp:EntityDataSource ID="EntityDataSource2" runat="server"
ConnectionString="name=AdventureWorksEntities"
DefaultContainerName="AdventureWorksEntities"
EnableUpdate="True" EntitySetName="Employee"
Select="" Where="it.EmployeeID = #selEmpID">
<WhereParameters>
<asp:ControlParameter ControlID="GridView1" Name="selEmpID" Type="Int32" PropertyName="SelectedValue" />
</WhereParameters>
</asp:EntityDataSource>
Is the "it" generate by EntityDataSource?
The "it" is the entity alias of Employee, but how can i define that?
For exmaple, if i include other entity by property below :
Include="Users,Permissions"
How to define different alias to different entity
e.g.:
emp = Employee usr = Users perm =
Permissions
"it" is the "Control Variable." You can change it using ObjectQuery's Name property.
ObjectQuery is what you get, for example out of your ObjectContext class, such as context.Products or context.Customers.
var query = context.Products;
query.Name = "products"; // changes "it" to "products"
Related
My Domain Classes simplified look like this:
class ScheduleTimeExp{
Data date
}
class ScheduleAction{
ScheduleTimeExp scheduleTimeExp
}
I have a select box in my gsp:
<g:select id="scheduleTimeExp" name="scheduleTimeExp.id" from="${tao.marketing.ScheduleTimeExp.list()}" optionKey="id" required="" value="${tao.marketing.ScheduleAction?.scheduleTimeExp?.id}" class="many-to-one"/>
Rather that letting the user select from all ScheduleTimeExp
from="${tao.marketing.ScheduleTimeExp.list()}"
I would like to show only those ScheduleTimeExp where a relation between ScheduleTimeExp and ScheduleAction does not exist for any other ScheduleAction. In other words only those time expressions which have not yet been selected in another ScheduleAction.
To enforce logic from presentation separation, you want to fill the list inside controller action:
def dataSource
def someAction() {
final Sql sql = new Sql( dataSource )
def scheduleTimeExps = sql.rows( 'select ste.id, ste.date from Schedule_Time_Exp ste where ste.id not in (select sa.Schedule_Time_Exp_id from Schedule_Action sa)' ).collect{ it as ScheduleTimeExp }
[ ..., scheduleTimeExps:scheduleTimeExps ]
}
Note: make sure the case and naming of the tables and columns are correct
and then in gsp:
<g:select .. from="${scheduleTimeExps}"/>
This is my Query =>
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment");
I want to display the values in variable Department in ViewBag or Anywhere.How can I do that?
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment").ToList()
and then work with list
You can use linq to Entities without executing raw queries as:
var department = dataContext.Department.Select(x=>x.Id).ToList();
If you are stubborn to use raw query, you can use as teo van kot has suggested above:
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment").ToList();
You can assign the list to ViewBag in controller as:
ViewBag.DepartmentIDs = department;
You can display the values in View as:
#{
foreach(var item in ViewBag.DepartmentIDs)
{
<span>#item <br/></span>
}
}
I have this code and the following EF model:
var modelToAdd = new Package
{
PackageID = model.LearningPackageID, // not auto-generated PK!
Name = model.Name,
Description = model.Description,
DateCreated = DateTime.Now,
ModuleID = model.ModuleID
};
activityRepo.AddPackage(modelToAdd);
This doesn't work too
var modelToAdd = new Pacakge
{
PackageID = model.LearningPackageID, // not auto-generated PK!
Name = model.Name,
Description = model.Description,
DateCreated = DateTime.Now
};
// assume moduleID is defined to a valid module ID (yes, tested)
var module = entities.Modules.Where( x => x.ID == moduleID);
module.Pacakges.Add(modelToAdd);
entities.SaveChanges();
Basically, there's a 1:M relationship beteen Modules and Packages. However, when I try to set ModuleID (which is gotten from a dropdown), for both cases I'll get:
A dependent property in a ReferentialConstraint is mapped to a store-generated column.
PackageID is alpha-numeric and is not auto-generated, either is ModuleID, as it is a FK
What should I do?
Please check that the Package.ModuleID conceptual property and store column (I suppose you are using a Devart Entity model, so you can check it in Model Explorer->Model.Store) have StoreGeneratedPattern set to None. The non-Entity Key referential constraint property can be neither Identity nor Computed.
I want to select all categories from a webservice. The webservice does not have a method for that, so I have to get all products, then select all categories that these products are in. When I recieve the data from the webservice, I make WebServiceProduct (ID, Name, etc) and WebServiceCategory (ID, Name, etc) objects of it.
This does not work:
IQueryable<SelectListItem> categories = (from p in webserviceProductRepository.GetProducts()
from c in p.Categories
select new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
}).Distinct().OrderBy(c => c.Text);
But it works when I first select it as a anonymus type:
var foo = (from p in webserviceProductRepository.GetProducts()
from c in p.Categories
select new
{
ID = c.ID.ToString(),
Name = c.Name
}).Distinct().OrderBy(c => c.Name);
IQueryable<SelectListItem> categories = from c in foo
select new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
};
I have also tried with a IEqualityComparer and overrided Equals and GetHashCode to check on WebServiceCategory.ID, but it does not work either.
So my question are, why is Distinct() working better on a anonymus type than on my WebServiceCategory object and SelectListItem?
Anonymous types have value equality. Reference types have reference equality. LINQ to Entities is following the default semantics for the types. But overriding Equals or implementing IEquatable won't work, because LINQ to Entities queries are translated to SQL, and LINQ to Entities cannot translate arbitrary C# code to SQL. Note that the overloads of, e.g., Distinct which take a comparer aren't supported in L2E.
You have one workaround already, in your second code example. Another would be to group by an anonymous type:
var categories = from p in webserviceProductRepository.GetProducts()
from c in p.Categories
group c by new { Id = c.ID, Name = c.Name } into g
order by g.Key.Name
select new SelectListItem
{
Value = g.Key.Id.ToString(),
Text = g.Key.Name
};
Have you tried implementing IEquatable<T> on SelectListItem?
I think, its an IQueryable object and IEqualityComparer's wont work for this object. Maybe this will help
IQueryable<SelectListItem> categories = (from p in webserviceProductRepository.GetProducts()
from c in p.Categories.Distinct()
orderby c.Name
select new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
});
1) I've a Product table with 4 columns: ProductID, Name, Category, and Price. Here's the regular linq to query this table.
public ActionResult Index()
{
private ProductDataContext db = new ProductDataContext();
var products = from p in db.Products
where p.Category == "Soccer"
select new ProductInfo { Name = p.Name, Price = p.Price}
return View(products);
}
Where ProductInfo is just a class that contains 2 properties (Name and Price). The Index page Inherits ViewPage - IEnumerable - ProductInfo. Everything works fine.
2) To dynamicaly execute the above query, I do this:
Public ActionResult Index()
{
var products =
db.Products
.Where("Category = \"Soccer\"")
.Select(/* WHAT SOULD I WRITE HERE TO SELECT NAME & PRICE?*/)
return View(products);
}
I'm using both 'System.Lind.Dynamic' namespace and the DynamicLibrary.cs (downloaded from ScottGu blog).
Here are my questions:
What expression do I use to select only Name and Price?
(Most importantly) How do I retrieve the data in my view? (i.e. What type the ViewPage inherits? ProductInfo?)
===================
EDIT
When I write .Select("new(Name, Price)"), I'm able to pass an object to the ViewData's Model property. Unfortunately, in order to use the Viewdata object, I'm asked to cast the Viewdata to a type. But, I do not know how to determine the type to do the casting.
====================
EDIT
Instead of the ViewData's Model property, I'm using simply the ViewData["products"]. To retrieve the content, I just place a IEnumerable cast before the ViewData, like this:
<% foreach(var item in (IEnumerable)ViewData["products"]){%>
<p><% = Html.Encode(item)%><p>
<%}%>
There are 2 situations:
1) If I select only one column (for instance, Name), everything work fine.
2) If I select more than 1 more columns (Name, Price), I get something like this
{Name=Soccer, Price=19.50}
{Name=Shin Pads, Price=11.59}
Why I just don't get something like
Soccer, 19.50
Shin Pads, 11.59
=================================
EDIT April 02 - 05h47 AM
I've define the GetPropertyValue Method (as your response suggets) as static in a static Class that I called 'HelperClass'. Now, this is the way I try to access the value of Name from my object.
<% = Html.Encode(HelperClass.GetPropertyValue(ViewData["product"], "Name")) %>
I get the following Exception:"Object reference not set to an instance of an object". And, the following line from the inside GetPropertyValue() his highlight.
Line 22: return propInfo.GetValue(obj, null);
Do I need to use new keyword? (where?)
Thanks for helping
Private Sub filter()
Dim coll = db.Products.Where(Function(x) x.Category.Equals("Soccer")) _
.Select(Function(x) GetObject(x.Name, x.Price))
End Sub
Private Function GetObject(ByVal name As String, ByVal price As String) As Object
Return new ProductInfo(name, price)
End Function
1) To generate a new projection type at runtime you can:
.Select("new(Name, Price)")
2) To read values from the object, you need to use reflection:
string name = GetPropertyValue(someObject, "Name");
...
public static object GetPropertyValue(object obj, string propName)
{
System.Reflection.PropertyInfo propInfo = obj.GetType().GetProperty(propName);
return propInfo.GetValue(obj, null);
}