Cannot implicitly convert type 'string' to 'System.Collections.Generic.ICollection<WebApplication2.Entry>' - asp.net

I used ado.net entity framework to connect database and have an .edmx file in project.. When I tried to reach objects in code side with object initializer I can see the object names but when I tried to enter a value into textarea in throws this error.Title is a table in database and entries is another tables data but because of both tables has relationship I can see Entries down of Title. What do I have to do? I do not understand anything.. thanks for helps here is the situation
Title a = new Title
{
Entries=textarea.InnerText,
};

Try below, you need to inititialize entry collection with your item by giving correct property value
Title a = new Title
{
Entries= new List<Entry>()
{
new Entry() {PropertyName =textarea.InnerText}
};
};

It's because your Entrires are of type ICollection<Entry> and you trying to store there string variable.

Related

How to use SQL Server 2008 stored procedure in asp.net mvc

I have created a simple stored procedure in SQL Server 2008 as:
CREATE PROCEDURE viewPosts
AS
SELECT * FROM dbo.Post
Now, I have no idea how to use it in controller's action, I have a database object which is:
entities db = new entities();
Kindly tell me how to use stored procedure with this database object in Entity Framework.
For Details check this link:
http://www.entityframeworktutorial.net/data-read-using-stored-procedure.aspx
Hope this will help you.
See article about 30% in:
In the designer, right click on the entity and select Stored Procedure mapping.
Click and then click the drop down arrow that appears. This exposes the list of all Functions found in the DB metadata.
Select Procedure from the list. The designer will do its best job of matching the stored procedure’s parameters with the entity properties using the names. In this case, since all of the property names match the parameter names, it maps every one correctly so you don’t need to make any changes. Note: The designer is not able to automatically detect the name of the field being returned.
Under the Result Column Bindings section, click and enter variable name. The designer should automatically select the entity key property for this final mapping.
The following code is what I use to initialize the stored procedure, then obtain the result into variable returnedResult, which in this case is the record id of a newly created record.
SqlParameter paramResult = new SqlParameter("#Result", -1);
paramResult.Direction = System.Data.ParameterDirection.Output;
var addParameters = new List<SqlParameter>
{
new SqlParameter("#JobID", EvalModel.JobID),
new SqlParameter("#SafetyEvaluator", EvalModel.SafetyEvaluator),
new SqlParameter("#EvaluationGuid", EvalModel.EvaluationGuid),
new SqlParameter("#EvalType", EvalModel.EvalType),
new SqlParameter("#Completion", EvalModel.Completion),
new SqlParameter("#ManPower", EvalModel.ManPower),
new SqlParameter("#EDate", EvalModel.EDate),
new SqlParameter("#CreateDate", EvalModel.CreateDate),
new SqlParameter("#Deficiency", EvalModel.Deficiency.HasValue ? EvalModel.Deficiency.Value : 0),
new SqlParameter("#DeficiencyComment", EvalModel.DeficiencyComment != null ? EvalModel.DeficiencyComment : ""),
new SqlParameter("#Traffic", EvalModel.Traffic.HasValue ? EvalModel.Traffic.Value : 0),
paramResult
};
// Stored procedure name is AddEval
context.Database.ExecuteSqlCommand("AddEval #JobID, #SafetyEvaluator, #EvaluationGuid, #EvalType, #Completion, #ManPower, #EDate, #CreateDate, #Deficiency, #DeficiencyComment, #Traffic, #Result OUTPUT", addParameters.ToArray());
var returnedResult = paramResult.Value;
NewEvaluationID = Convert.ToInt32(returnedResult);

XML validation error when updating Keyword metadata

Following on from my earlier question about creating Address Books (many thanks Peter!), I have a small throw-away console application doing just that and working great - but in addition I'm trying to update the metadata of a Keyword with the Item Id of the created Address Book.
Slightly shortened snippet ...
StaticAddressBook ab = new StaticAddressBook();
ab.Title = title;
ab.Key = key;
ab.Save();
// id is a correct Keyword TCM ID
Keyword k = tdse.GetObject(id, EnumOpenMode.OpenModeEdit);
if (k != null)
{
k.MetadataFields["addressbookid"].value[0] = ab.Id.ItemId;
k.Save(true);
}
I keep getting the following error on Save():
XML validation error. Reason: The element 'Metadata' in namespace
'uuid:2065d525-a365-4b45-b68e-bf45f0fba188' has invalid child element
'addressbookid' in namespace
'uuid:2065d525-a365-4b45-b68e-bf45f0fba188'. List of possible elements
expected: 'contact_us_email' in namespace
'uuid:2065d525-a365-4b45-b68e-bf45f0fba188'
But I know the Keyword has the correct Metadata assigned, (thats why I don't bother checking!). Shortened Tridion XML from a current keyword in question:
<tcm:Keyword>
<tcm:Data>
<tcm:MetadataSchemaxlink:type="simple"xlink:title="IP.Location.Metadata" xlink:href="tcm:49-2142-8" />
<tcm:Metadata>
<Metadata xmlns="uuid:2065d525-a365-4b45-b68e-bf45f0fba188">
<email>...</email>
<addressbookid>3</addressbookid>
<contact_us_email>...</contact_us_email>
<request_a_sample_email>...</request_a_sample_email>
<webinar_feedback_email>....</webinar_feedback_email>
</Metadata>
</tcm:Metadata>
<tcm:IsRoot>true</tcm:IsRoot>
</tcm:Data>
</tcm:Keyword>
Have I missed something can Keyword metadata not be updated in this way?
I guess I could look at the Core Service to update Keywords, but it seemed to to make sense to do everything within this application.
UPDATE
Order was key here, strangely!
The following code works:
ItemFields fields = k.MetadataFields;
System.Diagnostics.Debug.WriteLine(fields.Count);
string email = fields[1].value[1];
string contact = fields[3].value[1];
string request = fields[4].value[1];
string webinar = fields[5].value[1];
fields[1].value[1] = email;
fields[2].value[1] = ab.Id.ItemId;
fields[3].value[1] = contact;
fields[4].value[1] = request;
fields[5].value[1] = webinar;
k.Save(true);
Got caught out by the non-0-based index when getting/setting values and had to reassign existing fields back, in order.
Cheers
It seems that the order of the fields has changed in the Schema since that Component was created. At least the Schema expects contact_us_email in the position where you current have addressbookid.
There may be other changes, so I'd verify the order of fields in the Schema and make sure the Component(s) match, before you run your tool.

How to get Tridion item ID after created using Core Service

I am creating a new item using the Core Service in this post. However, the URI of the newly created item is tcm:0-0-0 instead of the actual TCM URI. the Title property is correct (and not New Component) but the WebDav path returns 'New Component' while .
What is the best way to get the URI of my newly created item?
client.Create(newComponent, null);
string newItemUri = newComponent.Id; // returns tcm:0-0-0
string webDavUrl = newComponent.LocationInfo.WebDavUrl; // returns New%20Component
string title = newComponent.Title; // correct
Second parameter of Create method are ReadOptions. They are used to specify how the item will be read back. In your example you have it set to null, meaning you will not read it back. What you should do is set ReadOptions and assign item read back to a variable, like this:
newComponent = (ComponentData) client.Create(newComponent, new ReadOptions());
Check out Ryan's code at http://blog.building-blocks.com/uploading-images-using-the-core-service-in-sdl-tridion-2011. He uses client.Save to get the saved Component, from which he's able to access the ID.

Assign Business entity to hidden variable

Say for example if I have a business entity -> Customer, which has customerId, customerName and customerType. I have created an asp:Hidden Variable hdnCustomer to runat="server"
If I wanted to serialize the value of the customer business entity (in the code behind) to the hdnCustomer then how would I do that? Also once serialized how would I deserialize it?
// Pseudo code
Collection<Customer> customerList = new Collection<Customer>();
customerList = BusinessAccess.GetCustomerList();
hdnCustomer = serialize and assign the value of 'customerList' to hdnCustomer;
...
...
// Later on a select index change of one of the drop down lists
Inside the event handler for the drop down list:
{
Collection<Customer> customerList = new Collection<Customer>();
customerList = deserialize the value from hdnCustomer
int a = Convert.ToInt32(ddlDropDown.SelectedValue);
foreach(a in customerList)
{
// Do something
}
}
You can serialise to and from XML using XmlSerializer:
http://support.microsoft.com/kb/815813
However, if you just store the object in the ViewState[] collection that should work better:
ViewState["Customer"] = customerList;
It does the same thing: store the serialisable object in the page, hidden from the user: but it won't be in a human-readable format.
(edit: To deserialise, just get the value of ViewState["Customer"], checking for a null before using it!)
edit 2: a useful link about storing objects in ViewState:
http://www.beansoftware.com/ASP.NET-Tutorials/ViewState-In-ASP.NET.aspx
Hope that helps.
I think .net has already providing some classes to do so, look at this example

Committing new data to database via EF, Errors ensue with Attaching/Adding

So I'm starting out with EF on my website (C#) and Ive run into a bit of a snag. A user can either create or modify data and they will do that with the selection screen (page 1). If a user selects to create new data, I will perform the following code:
Program newProg = new Program();
using (DatabaseEntities context = new DatabaseEntities())
{
Guid id = new Guid(list.SelectedValue);
var itemString = from item in context.Set where item.Id == id select item;
Item selectedItem = itemString.ToList()[0];
newProg.Items.Add(selectedItem);
context.AddToProgramSet(newProg);
context.Detach(newProg);
}
Pretty much creating a new instance of the 'Program' which will be passed along each user control until the user is ready to submit to the database. At that point the following code will be executed:
using (DatabaseEntities context = new DatabaseEntities())
{
context.AddToProgramSet(this.SummaryControl.SelectedProgram);
context.SaveChanges();
}
Unfortunately when I get there, I receive the following message:
The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.
at this line:
context.AddToProgramSet(this.SummaryControl.SelectedProgram);
Also, when I add the following line prior to the previous:
context.Attach(this.SummaryControl.SelectedProgram);
I get this error:
An object with a null EntityKey value cannot be attached to an object context.
Any help would be greatly appreciated. Thanks.
The root cause of this error is that you are attempting to add an Entity as a new Entity that already has its primary key set.
At what point do you add the Entities to your SummaryControl? Your first code snippet shows you adding the Entity:
...
newProg.Items.Add(selectedItem);
context.AddToProgramSet(newProg);
context.Detach(newProg);
...
Then you appear to add it again:
using (DatabaseEntities context = new DatabaseEntities())
{
context.AddToProgramSet(this.SummaryControl.SelectedProgram);
context.SaveChanges();
}
If newProg and this.SummaryControl.SelectedProgram are the same Entity, you've attempted to add it twice. Remove the context.AddToProgramSet(newProg); from the first snippet, do you work on the Entity, then add it to the ProgramSet.
Dave is right that the root cause is that the entity already has a primary key.
One thing that you do not show in your code is how:
Program newProg = new Program();
Becomes:
this.SummaryControl.SelectedProgram
One way that you could fix it is by saving newProg to the database before you start adding Items to it.

Resources