I've set up a local service and a Windows Azure database. I can access the Azure database and retrieve data from all rows but only from one column at at time.
The database has a table called People with each 'record' treated as a Person. One of the columns in the table is 'Name' and I can retrieve all of the names using:
public List<string> GetAllPeople()
{
string query = #"SELECT value Person.Name FROM DataEntities.People AS Person";
List<string> resultsAsStrings = new List<string>();
using (var context = new DataEntities())
{
ObjectQuery<string> results = context.CreateQuery<string>(query);
foreach (string result in results)
{
if (result != null)
{
resultsAsStrings.Add(result);
}
}
}
return resultsAsStrings;
}
How would I go about changing the query so that I could retrieve a list of ALL of the Person records with ALL columns in the table as opposed to just the name field?
Is there a better way to read data from an Azure table?
Cheers!
Edit:
When I change the query to:
#"SELECT value Person FROM DataEntities.People AS Person";
It returns null and my WP7 app crashes. (I also adjusted the code so that it accepted Person instead of string. E.G ObjectQuery
Try changing the call to CreateQuery:
From: CreateQuery<string>
To: CreateQuery<Person>
This is required because if you select a Person this won't be a string, but a Person.
Now, could you try not using the type (Person) as alias? Try something like this:
SELECT VALUE pers FROM DataEntities.People AS pers
And why don't you simply use context.People?
Related
I am just starting with linq and entity framework in general and I have a question that may seem naive to all of the advanced users!
I have the following code :
var allDocuments = (from i in companyData.IssuedDocuments select i.IssuedDocumentId).ToList<int>();
var deletedDocuments = allDocuments.Except(updatedDocuments);
and I need to delete all the entities in companyData that their id is stored in deletedDocuments in a disconnected scenario.
Could you please show me a way to do this in an efficient manner?
You could avoid fetching all the ids by specifying you only want deleted ids like this:
var deletedIds = from i in companyData.IssuedDocuments
where !updatedIds.Contains(i.IssuedDocumentId)
select i.IssuedDocumentId
Now if companyData.IssuedDocuments is a DbSet you can tell EF to delete them like this:
foreach (var id in deletedIds)
{
var entity = new MyEntity { Id = id };
companyData.IssuedDocuments.Attach(entity);
companyData.IssuedDocuments.Remove(entity);
}
dbContext.SaveChanges();
This will issue multiple DELETE statements to the database without fetching the full entities into memory.
If companyData.IssuedDocuments is your repository then you could load the full entities instead of just the ids:
var deleted = from i in companyData.IssuedDocuments
where !updatedIds.Contains(i.IssuedDocumentId)
select i
foreach (var entity in deleted)
companyData.IssuedDocuments.Delete(entity);
dbContext.SaveChanges();
Again EF issues multiple DELETE statements to the database
If you can upgrade then EF6 has introduced a RemoveRange method on the DbSet that at you could look at. It may send a single DELETE statement to the database - I haven't tried it yet.
If performance is still an issue then you have to execute sql.
References:
RemoveRange
Deleting an object without retrieving it
How should I remove all elements in a DbSet?
companyData.RemoveAll(x=>deletedDocuments.Contains(x.Id));
I suppose the companyData is a IEnumerable type. The type T contains an Id property, which is the Id of the data. Then deletedDocuments contains the ids of all the documents that we want to remove.
One thing that's important and I should note it here is that the deletion of the documents happens in memory and it doesn't execute it in a db. Otherwise you should provide us with the version of entity framework you use and how you access you implelemnt your CRUD operations against your db.
Firstly I would like to thank you all for your suggestions.
I followed Christos Paisios suggestion but I was getting all kinds of exceptions when I was trying to persist the changes to the DB and the way that I finally managed to solve the issues was by adding the following override in my DbContext class
public override int SaveChanges()
{
var orphanedResponses = ChangeTracker.Entries().Where(
e => (e.State == EntityState.Modified || e.State == EntityState.Added) &&
e.Entity is IssuedDocument &&
e.Reference("CompanyData").CurrentValue == null);
foreach (var orphanedResponse in orphanedResponses)
{
IssuedDocuments.Remove(orphanedResponse.Entity as IssuedDocument);
}
return base.SaveChanges();
}
I am working with code first approach in EDM and facing an error for which I can't the solution.Pls help me
LINQ to Entities does not recognize the method 'Boolean
CheckMeetingSettings(Int64, Int64)' method, and this method cannot be
translated into a store expression.
My code is following(this is the query which I have written
from per in obj.tempPersonConferenceDbSet
where per.Conference.Id == 2
select new PersonDetials
{
Id = per.Person.Id,
JobTitle = per.Person.JobTitle,
CanSendMeetingRequest = CheckMeetingSettings(6327,per.Person.Id)
}
public bool CheckMeetingSettings(int,int)
{
///code I have written.
}
Please help me out of this.
EF can not convert custom code to SQL. Try iterating the result set and assigning the property outside the LINQ query.
var people = (from per in obj.tempPersonConferenceDbSet
where per.Conference.Id == 2
order by /**/
select new PersonDetials
{
Id = per.Person.Id,
JobTitle = per.Person.JobTitle,
}).Skip(/*records count to skip*/)
.Take(/*records count to retrieve*/)
.ToList();
people.ForEach(p => p.CanSendMeetingRequest = CheckMeetingSettings(6327, p.Id));
With Entity Framework, you cannot mix code that runs on the database server with code that runs inside the application. The only way you could write a query like this, is if you defined a function inside SQL Server to implement the code that you've written.
More information on how to expose that function to LINQ to Entities can be found here.
Alternatively, you would have to call CheckMeetingSettings outside the initial query, as Eranga demonstrated.
Try:
var personDetails = obj.tempPersonConferenceDbSet.Where(p=>p.ConferenceId == 2).AsEnumerable().Select(p=> new PersonDetials
{
Id = per.Person.Id,
JobTitle = per.Person.JobTitle,
CanSendMeetingRequest = CheckMeetingSettings(6327,per.Person.Id)
});
public bool CheckMeetingSettings(int,int)
{
///code I have written.
}
You must use AsEnumerable() so you can preform CheckMeetingSettings.
Linq to Entities can't translate your custom code into a SQL query.
You might consider first selecting only the database columns, then add a .ToList() to force the query to resolve. After you have those results you van do another select where you add the information from your CheckMeetingSettings method.
I'm more comfortable with the fluid syntax so I've used that in the following example.
var query = obj.tempPersonConferenceDbSet
.Where(per => per.Conference.Id == 2).Select(per => new { Id = per.Person.Id, JobTitle = per.Person.JobTitle })
.ToList()
.Select(per => new PersonDetails { Id = per.Id,
JobTitle = per.JobTitle,
CanSendMeetingRequest = CheckMeetingSettings(6327, per.Person.Id) })
If your CheckMeetingSettings method also accesses the database you might want to consider not using a seperate method to prevent a SELECT N+1 scenario and try to express the logic as part of the query in terms that the database can understand.
How do you find items in SSRS by ID? I tried to use the id returned by another find result, a new guid to string and small random string all of which return the same error:
The ID field has a value that is not valid. ---> Microsoft.ReportingServices.Diagnostics.Utilities.InvalidElementException: The ID field has a value that is not valid.
Here is the code:
var request = new FindItemsRequest
{
Conditions = new[] { new SearchCondition { Name = "ID", Value = "test"} },
Folder = "/"
};
return _ssrsService
.FindItems(request)
.Items
I'm using SSRS 2005.
Pretty sure this can't be done through the SSRS service. Ended up finding all objects then using LINQ to filter down to the ID I need.
The MS documentation on the FindItems method says:
Applications that use FindItems typically accept user input for specific properties and property values. The searchable properties are Name, Description, CreatedBy, CreationDate, ModifiedBy, and ModifiedDate. The items that are returned are only those for which a user has Read Properties permission.
I would like to control how Linq queries my database programmatically. For instance, I'd like to query the column X, column Y, or column Z, depending on some conditions.
First of all, I've created an array of all the properties inside my class called myPropertyInfo.
Type MyType = (typeOf(MyClass));
PropertyInfo[] myPropertyInfo = myType.GetProperties(
BindingFlags.Public|BindingFlags.Instance);
The myPropertyInfo array allows me to access each property details (Name, propertyType, etc) through the index [i].
Now, how can I use the above information to control how Linq queries my DB?
Here's a sample of a query I'd like to exploit.
var myVar = from tp in db.MyClass
select tp.{expression};
Expression using myPropertyInfo[i] to choose which property (column) to query.
I'm not sure if that's the way of doing it, but if there's another way to do so, I'll be glad to learn.
EDIT:
I believe the right expression the one used by #Gabe. In fact, I'd like to make queries on the fly. Here's the reason: I've (i) a table Organizations (Ministries, Embassies, International Organizations, such as UN, UNPD, UNICEF, World Bank, etc, and services depending on them). I've (ii) an other table Hierarchy which represents the way those organizations are linked, starting by which category each one belongs to (Government, Foreign Missions, private sector, NGO, etc.)
Each column representing a level in the hierarchy, some rows will be longer while other will be shorter. Many rows' columns will share the same value (for instance 2 ministries belonging to the government, will have "Government" as value for the column 'Level 1').
That's why, for each row (organization), I need to go level by level (i.e. column by column).
if you're using Entity Framework, not LINQ to SQL, there is wonderful Entity Sql
and you can use it as
object DynamicQuery(string fieldName, object fieldValue) {
string eSql=string.Format("it.{0} = #param", fieldName);
return db.Where(eSql, fieldValue).FirstOrDefault();
}
hope this helps
MSDN has the following example, you see that you can dynamicly change strings used to access ProductID field, and as far as i remember event rename it.
using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
try
{
// Use the Select method to define the projection.
ObjectQuery<DbDataRecord> query =
advWorksContext.Product.Select("it.ProductID, it.Name");
// Iterate through the collection of data rows.
foreach (DbDataRecord rec in query)
{
Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
}
Also you can even do the following (again from MSDN)
using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
string myQuery = #"SELECT p.ProductID, p.Name FROM
AdventureWorksEntities.Product as p";
try
{
foreach (DbDataRecord rec in
new ObjectQuery<DbDataRecord>(myQuery, advWorksContext))
{
Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
}
It sounds like you want to make a Queryable on-the-fly. I haven't tried it, but this might give you a start:
var myVar =
Queryable.Select(
db.MyClass,
Expression.Property(
Expression.Parameter(
typeof(MyClass), // this represents the type of "tp"
"tp"
),
myPropertyInfo[i]
)
)
After going through Entity Framework I have a couple of questions on implementing auditing in Entity Framework.
I want to store each column values that is created or updated to a different audit table.
Right now I am calling SaveChanges(false) to save the records in the DB(still the changes in context is not reset). Then get the added | modified records and loop through the GetObjectStateEntries. But don't know how to get the values of the columns where their values are filled by stored proc. ie, createdate, modifieddate etc.
Below is the sample code I am working on it.
// Get the changed entires( ie, records)
IEnumerable<ObjectStateEntry> changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
// Iterate each ObjectStateEntry( for each record in the update/modified collection)
foreach (ObjectStateEntry entry in changes)
{
// Iterate the columns in each record and get thier old and new value respectively
foreach (var columnName in entry.GetModifiedProperties())
{
string oldValue = entry.OriginalValues[columnName].ToString();
string newValue = entry.CurrentValues[columnName].ToString();
// Do Some Auditing by sending entityname, columnname, oldvalue, newvalue
}
}
changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
foreach (ObjectStateEntry entry in changes)
{
if (entry.IsRelationship) continue;
var columnNames = (from p in entry.EntitySet.ElementType.Members
select p.Name).ToList();
foreach (var columnName in columnNames)
{
string newValue = entry.CurrentValues[columnName].ToString();
// Do Some Auditing by sending entityname, columnname, value
}
}
Here you have two basic options:
Do it at the database level
Do it in the c# code
Doing it at the data base level, means using triggers. In that case there is no difference if you are using enterprise library or another data access technology.
To do it in the C# code you would add a log table to your datamodel, and write the changes to the log table. When you do a save changes both the changes to the data and the information which you wrote to the log table would be saved.
Are you inserting the new record using a stored proc? If not (i.e. you are newing up an object, setting values, inserting on submit and then saving changes the new object id will be automatically loaded into the id property of the object you created. If you are using a stored proc to do the insert then you need to return the ##IDENTITY from the proc as a return value.
EX:
StoreDateContext db = new StoreDataContext(connString);
Product p = new Product();
p.Name = "Hello Kitty Back Scratcher";
p.CategoryId = 5;
db.Products.Add(p);
try
{
db.SaveChanges();
//p.Id is now set
return p.Id;
}
finally
{
db.Dispose;
}