ADO.NET Data Services: Non-Asynch Calls? - asynchronous

I have a question that I'm struggling with in ADO.NET Data Services:
When assembling an Entity for storage I need to get a related value from a lookup file. For example a person has a status code assigned of 'Pending' which is in a table called StatusCodes.
In Entity Framework, I'd need to set the value of person.StatusCode equal to an instance of the StatusCode. In the Entity Framework or in LINQ2Sql I'd so something like this:
var person = Person.CreatePerson(stuff);
var statCode = myContext.StatusCodeSet.Where(sc => sc.Description == "Pending").FirstOrDefault();
person.StatusCode = statCode;
// ...more code here...
myContext.BeginSaveChanges(SaveChangesOptions.Batch,
new AsyncCallback(OnSaveAllComplete),
null);
The query for the statCode won't work in ADO.NET Data Services and I get a runtime error saying the function is not supported. I assume it's because the statCode lookup is not an Async call.
However,
var person = Person.CreatePerson(stuff);
var query = from stat in myContext.StatusCodeSet
where stat.Description == "Pending"
select stat;
var dsQuery = (DataServiceQuery<StatusCode>)query;
dsQuery.BeginExecute(
result => tutorApplication.StatusCode = dsQuery.EndExecute(result).FirstOrDefault(), null);
// ...more code here...
myContext.BeginSaveChanges(SaveChangesOptions.Batch,
new AsyncCallback(OnSaveAllComplete),
null);
doesn't work either due to the Async nature of the query, the result won't be back before the person save happens.
Am I approaching this correctly?
Thanks

After sleeping on this I came up with the following:
var person = Person.CreatePerson(stuff);
var appStatPending = new StatusCode()
{
StatusCodeId = (int)StatusCodes.Pending,
Code = "Pending",
Description = "Pending",
EffectiveDate = DateTime.Now,
EnteredBy = "",
EnteredDate = DateTime.Now
};
myContext.AttachTo("StatusCodeSet", appStatPending);
person.StatusCode = appStatPending;
myContext.SetLink(tutorApplication, "StatusCode", appStatPending);
// ...more code here...
myContext.BeginSaveChanges(SaveChangesOptions.Batch,
new AsyncCallback(OnSaveAllComplete),
null);
I can create a local copy of the status code and link it into the context. It's important to new up the appStatPending rather than doing a StatusCode.CreateStatusCode() since doing that will add a new StatusCode to the database when the person graph persisted. For the same reason it's important to do the AttachTo("StatusCodeSet", appStatPending) since doing myContext.AddToStatusCodeSet() will also add a new entry to the StatusCodes table in the database.

Related

Automapper seems to be caching data

Automapper version, which i am using in project is, AutoMapper, Version=6.0.2.0
When i run this for the first time, there is a record available in person object, which gets mapped to employee object. In the subsequent runs, though person object does not have any data, employee object holds the previously stored data and it appears to be cached data.
how can i get rid of this ?
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Person, Employee>();
});
person pobj = new person();
pobj.FirstName = "Adam";
pobj.LastName = "Smith";
pobj.Address = "some address";
Mapper.CreateMap<Person, Employee>();
Employee emp = Mapper.Map<Employee>(pobj);

Get Dynamics CRM contact parentcustomerid

I need to retrieve full name and parent account of contact in Dynamics CRM.
I am using following code:
ColumnSet cols = new ColumnSet(new String[] { "fullname", "parentcustomerid" });
Entity retrContact = (Entity)orgService.Retrieve("contact", contactID, cols);
fullName = retrContact.Attributes["fullname"];
parentAccount = retrContact.Attributes["parentcustomerid"];
nameStr = fullName.ToString();
companyStr = parentAccount.ToString();
My problem is that companyStr getting "Microsoft.Xrm.Sdk.EntityReference" instead of Name value.
parentAccount contains following:
LogicalName "account" string
Name "Microsoft Corp" string
RowVersion null string
How can I get Name string?
The parentcustomerid object is an EntityReference object which has the name you're looking for. This code works:
ColumnSet cols = new ColumnSet(new string[] { "fullname", "parentcustomerid" });
Entity retrContact = (Entity)orgService.Retrieve("contact", new Guid("{9DF2ACC2-0212-E611-80E4-6C3BE5A83B1C}"), cols);
var parentAccount = (EntityReference)retrContact.Attributes["parentcustomerid"];
var companyStr = parentAccount.Name;
You should probably fetch the parentAccount from server (please refer to EntityReference.Name Property
This property is not automatically populated unless the EntityReference object has been retrieved from the server.
E.g. you should fetch the data from server using the Id parentcustomerid, somewhat like
Entity Account = service.Retrieve(Account.EntityLogicalName, parentAccount.Id, new ColumnSet(true));
You can for sure replace Account.EntityLogicalName with "account" string.

How to save a related entity using Entity Framework in asp.net

I am pretty new to Entity Framework. I am getting an error as
An object with a temporary EntityKey value cannot be attached to an
object context
I think I am doing something wrong.
I have a Customer table and Address table where the Address table has customer's ID as foreign key.
I want to add a new address to the customer entity and keep in session and in next call I want to save it. this is only an example.
using (var db = new MyModel())
{
Customer cust = db.Customers.SingleOrDefault(c => C.ID == 1);
Address addr = new Address();
addr.Street = "123 super st";
cust.Addresses.Add(addr);
Session["customer"] = cust;
}
Customer SessionCustomer = (Customer)Session["customer"];
Customer.Comments = "Added new address";
using (var db = new MyModel())
{
db.Customers.Attach(SessionCustomer); //This throws exception: An object with a temporary EntityKey value cannot be attached to an object context
db.ObjectStateManager.ChangeObjectState(SessionCustomer, System.Data.EntityState.Modified);
db.SaveChanges();
}
Any help is appreciated. thank you.
Try using db.Customers.AddObject() for reattaching object to datacontext.
Take also a look at this: http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.addobject.aspx
Cheers

Returning a column from a linked table in LINQ to SQL

My problem is that I am trying to return a simple query that contains an object Story. The Story object has a UserId in the table which links to aspnet_users' UserId column. I have created a partial class for Story that adds the UserName property since it does not exist in the table itself.
The following query gets all stories; however, a pagination helper takes the query and returns only what's necessary once this is passed back to the controller.
public IQueryable<Story> FindAllStories(){
var stories = (from s in db.Stories
orderby s.DateEntered descending
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
}
);
return stories;
}
When the helper does a .count() on the source it bombs with the following exception:
"Explicit construction of entity type 'MyWebsite.Models.Story' in query is not allowed."
Any ideas? It's not a problem with the helper because I had this working when I simply had the UserName inside the Story table. And on a side note - any book recommendations for getting up to speed on LINQ to SQL? It's really kicking my butt. Thanks.
The problem is precisely what it tells you: you're not allowed to use new Story as the result of your query. Use an anonymous type instead (by omitting Story after new). If you still want Story, you can remap it later in LINQ to Objects:
var stories = from s in db.Stories
orderby s.DateEntered descending
select new
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
};
stories = from s in stories.AsEnumerable() // L2O
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
...
};
If you really need to return an IQueryable from your method and still need the Username of the user you can use DataContext.LoadOptions to eagerload your aspnet_user objects.
See this example.

How to delete in linq to sql?

I am very new to linq to sql and I am not sure how to actually delete a record.
So I been looking at this tutorial
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
So for Update they have
NorthwindDataContext db = new NorthwindDataContext();
Product product = db.Products.Single(p => p.ProductName == "Toy 1");
product.UnitPrice == 99;
product.UnitsInStock = 5;
db.SubmitChanges();
For delete they have
NorthwindDataContext db = new NorthwindDataContext();
var toyProducts = from p in db.Producsts
where p.ProductName.Contains("Toy")
select p;
db.Products.RemoveAll(toyProducts);
db.SubmitChanges();
So do I have to query every time, to get the record in order to delete that record? Like I can sort of see doing this with update since you need to give it a record which to update first and then make the changes so I understand the querying part but not with delete.
Like can't you just send in what you want to delete and it goes and deletes it? why do you have to first get it and then tell it to be deleted?
Is that not 2 hits on the database?
Also I have foreign key relationship that I am trying to get to work. So I have this
public ViewResult(string param1, string param2)
{
Table A = new Table A
A.Field1 = param1;
A.Field2 = param2;
Delete(A);
}
private void Delete(Table A)
{
DbContext.A.DeleteAllOnsubmit(A.TableB);
DbContext.A.DeleteAllOnSubmit(A.TableC);
DbContext.A.DeleteOnSubmit(A);
}
So this fails it comes up with this message "Cannot remove an entity that has not been attached."
So I can see why the first 2 lines would fail in the delete method, since I made a new object and their is nothing in the object that has any information about TableB and TableC.
I however can't see why the last line still fails even if the 2 other lines where not there.
Like how I thought it would work it would take my Table A class object that I passed in and look through the table for that information contained in it. It does not seem to be the case though.
So do I first have to take the information out and then do a query to get it and then delete it, like in the example?
Also what is the difference between removeAll() and say DeleteAllOnSubmit().
Like I said I am new to linq to sql and have not been able to sit down and read a book on it due to time constraints. Once I have more time I will read through a book probably.
Thanks
You have several questions in your one question, but I will start with the simplest, about attaching, if you already have the primary key. If you don't have the primary key then I have always just done a fetch then a delete, but, whenever I do a fetch I tend to store the primary key for updates and deletes.
It will delete off of the primary key, but if you have that then just attach as I do below and call delete. I don't pass around the object needed by DLINQ as I want to be able to change it if I want, so I pass in a different User object and just pull the PK from the business class and put it into the DAO class.
var db = new MeatRequestDataContext();
if (input.UserID > 0)
{
entity = new User()
{
UserID = input.UserID
};
db.Users.Attach(entity);
db.Users.DeleteOnSubmit(entity);
}
this is a simple way to delete row from table by linq query.may be it helps .
var summary_delete = database.summeries.Find(id);
var delete = database.summeries.Remove(summary_delete);
database.SaveChanges();
reference : http://mvc4asp.blogspot.in/2013/09/how-to-delete-table-row-in-sql-database.html
Inserted_LINQDataContext db = new Inserted_LINQDataContext();
Item itm = new Item();
int ID = Convert.ToInt32(TextBox1.Text);
var DeleteID = from d in db.Items
where d.id == ID
select d;
db.Items.DeleteAllOnSubmit(DeleteID);
db.SubmitChanges();
Label2.Text = "Record deleted Successfully.";
TextBox1.Text = "";
where Item is Table name, Linserted_LINQDataContext is your Linq DB name, id is the Column name in Item table. Items is the alias name of Item table in linq.
SupportDataDataContext Retrive = new SupportDataDataContext();
// SupportDataDataContext delete = new SupportDataDataContext();
Topic res = Retrive.GetTable<Topic>().Single(t => t.ID == topicID);
if (res != null)
{
Retrive.Topics.DeleteOnSubmit(res);
Retrive.SubmitChanges(ConflictMode.ContinueOnConflict);
}
I know the question is old but this may be useful to someone:
"YourDataContext" dc = new "yourDataContext";
"YourTable" element = dc."YourTable".First(a => a.Id == 12345);
dc."YourTable".DeleteOnSubmit(element);
dc.SubmitChanges();

Resources