I tried to recreate a code (that I've seen in a video) in Visual Studio 2013 (c#) that was written in VS2008 (c#):
I've tried both EF 6 and EF 5 version options same result..searched web and MSDN with no luck.
Here is my code with comments showing the errors I got:
private CoffeeShopDBEntities cse = new CoffeeShopDBEntities();
private void AddProductsToTabbedPanel()
{
// using (CoffeeShopDBEntities context = new CoffeeShopDBEntities())
//--found this on msdn..got rid of old but end up w/2 new errors see below
{
//the foreach code below goes here
}
foreach(TabPage tp in tabControl1.TabPages)
{
ObjectQuery<tblProduct> filteredProduct = new ObjectQuery<tblProduct>
("SELECT VALUE P FROM tblProducts AS P", cse);
//when 'context' used 1)possible mistaken empty statment
//2)the name 'context' doesnt exist in the current context
//when 'cse'used :
//Error 1 The best overloaded method match for 'System.Data.Objects.ObjectQuery<P.tblProduct>.ObjectQuery(string, System.Data.Objects.ObjectContext)' has some invalid arguments
//Error 2 Argument 2: cannot convert from 'P.CoffeeShopDBEntities' to 'System.Data.Objects.ObjectContext'
foreach (tblProduct tprod in filteredProduct)
{
Button b = new Button();
b.Text = tprod.Description;
tp.Controls.Add(b);
}
}
}
I found a similar issue on Stack Overflow and the reply states it's a syntax error but doesn't point out where.
You are getting errors because ObjectQuery is looking for an ObjectContext which comes with EF 4.0 and below. The CoffeeShopDBEntities is of the DBContext type which comes with anything EF 4.1 and above.
I would suggest changing your query to:
List<tblProduct> filteredProducts = cse.tblProducts.ToList();
If you want to read more on the ObjectContext vs. DBContext, you can check out this link:
http://www.c-sharpcorner.com/UploadFile/ff2f08/objectcontext-vs-dbcontext/
Related
I have this control (db is the Entity Framework context):
if (db.Sites.Any(s => s.Name.Equals(name))) throw new NameAlreadyInUseException(name);
When I run my tests and debug it fails giving me the error:
Error CS0103: the name 's' does not exist in the current context.
I honestly can't get my head around it and Google hasn't really been helping... any help is appreciated, thanks in advance. Isn't s used correctly here? (I'm still learning, so maybe I missed something but my code here looks ok to me)
Edit:
the debugger triggers the error on this line and I am not using s in any other place other than inside that if statement. (I edited the line to show what happens with the if)
Edit2: complete code of the function
public void CreateSiteOnDb(string connectionString, string name, int timezone, int sessionExpirationTimeInSeconds,
double minimumBidIncrement)
{
CheckInput_CreateSiteOnDb(connectionString, name, timezone, sessionExpirationTimeInSeconds, minimumBidIncrement);
try
{
using (var db = new AuctionSiteContext(connectionString))
{
if (db.Sites.Any(s => s.Name.Equals(name))) throw new NameAlreadyInUseException(name);
var site = new Entities.Site
{
Name = name,
Timezone = timezone,
MinimumIncrement = minimumBidIncrement,
SessionExpirationInSeconds = sessionExpirationTimeInSeconds
};
db.Sites.Add(site);
db.SaveChanges();
}
}
catch(NameAlreadyInUseException)
{
throw;
}
catch(Exception)
{
throw new UnavailableDbException();
}
}
Edit3: Error as shown during debugging
It is not in the right scope.
In the screenshot you are in the scope of CreateSiteOnDb -> try -> using, but s does not belong to that context.
In very basic terms s => .... is converted to function of a class, and it is called from inside Any. so let's assume that our expression is function named Steve. Steve would look like this:
bool Steve(ISite s)
{
return s.Name.Equals(name);
}
this means s is the parameter of Steve, and is only valid inside Steve, which becomes CreateSiteOnDb -> try -> using -> Any -> Steve
So to see s you need to be in two more levels. Please, put your cursor inside the expression and then put a breakpoint.
I've had to jump in to a complex project and am making unit tests for a particular repository in a WEB API service. The database CRUD is handled by the Entity Framework.
private class IntegrationScope : AutoRollbackTransactionTestScope<DocumentRepository>
{
public IntegrationScope()
{
DependencyResolverMock = MockDependencyResolverFor<IResourceUrlBuilder, ResourceUrlBuilder>(new ResourceUrlBuilder());
LoggingProviderMock = new Mock<ILoggingProvider>();
// use real document micro service AutoMapper & Unity configuration
AutoMapperConfig.RegisterMaps(Mapper.Configuration, DependencyResolverMock);
UnityConfig.RegisterTypes(TestScopeContainer);
//Set the DomainId
TestId = Guid.NewGuid();
TestDocument = BuildDocument(TestId);
// get the real object
DocumentStoreDbContext = TestScopeContainer.Resolve<IDocumentDbContext>();
InstanceUnderTest = new DocumentRepository(DocumentStoreDbContext);
}
public static Web.Service.DocumentStore.Domain.Document BuildDocument(Guid documentId)
{
// Invoke GetBytes method.
byte[] array = Encoding.ASCII.GetBytes("Byte Repository Test");
return Builder<Web.Service.DocumentStore.Domain.Document>
.CreateNew()
.With(t => t.Id = documentId)
.With(t => t.Data = array)
.Build();
}
When it gets to the DocumentStoreDbContext line, there is no compilation error but i get a run-time error saying that the object name is invalid:
After doing some research this error appears to be because the database/table doesn't exist, however I can see that it does exist:
What am I doing wrong and how do I fix it?
InnerException displays the table name as DocumentStore.Documents, but your SSMS screenshot shows dbo.Documents.
Could this be the cause?
I am trying make a join in entity framework and display datas in a label but i get an error like "FileLoadException was unhandled by user code".Here is my codebehind:
protected void display() {
AspNetOrnekEntities entity = new AspNetOrnekEntities();
var everything = (from insan in entity.insanlar
join renk in entity.renkler on insan.SevdigiRenk equals renk.Renk
select new
{
kisiId = insan.KisiId,
renkId = renk.RenkId
});
foreach (var data in everything)
{
Label1.Text += data.kisiId + " " + data.renkId + "<br/>";
}
}
I call "display" in page_load and error comes from that line. I think problem occurs because of first line of the display method because I turned all other lines into comments and problem still occurs. I am using Model1.edmx as connection.
update the EF using the Package manager Console
I'm trying to query a view using TouchDB in C#. I used the binding between TouchDB and MonoTouch available here : https://github.com/mono/monotouch-bindings/tree/master/Couchbase
When the emit delegate method is called, I get a "System.Runtime.InteropServices.MarshalDirectiveException" saying "The type MonoTouch.Foundation.NSObject which is passed to unmanaged code must have a StructLayout attribute."
I found this bug report here : https://bugzilla.xamarin.com/show_bug.cgi?id=4781 that is similar to my problem but there isn't any updates since July 27, 2012.
Here's my test code :
CouchTouchDBServer server = new CouchTouchDBServer ();
CouchDatabase database = server.GetDatabase ("grocery-sync");
database.TracksChanges = true;
// Create a test view
design = database.DesignDocumentWithName ("grocery");
design.DefineView ("testView", (doc,emit) => {
emit (doc, doc); // Crashes here
}, "1.0");
// Query the view
CouchQuery query = design.CereateQuery("testView");
RestOperation op = query.Start();
string response = op.ResponseBody.AsString;
Console.WriteLine(response);
Has anyone successfully queried a view on TouchDB with MonoTouch? Thanks for your help
It seems to be a bug of Xamarin
I'm using an Oracle 11g database with the ADO.NET Entity Data Model. Every now and then I run into this error and I have no idea what's causing it. I'm assuming it's something in the EDMX file or the designer file for it but I can't seem to figure it out. I've deleted the model, added it, updated, etc multiple times and can't figure out the issue. It works on other pages but this one seems to be a problem.
This has happened before, but simply removing and re-adding the table worked. Any ideas on how to fix this?
using (ODSData.Entities entities = new Entities())
{
var info = from item in entities.ODS_VALIDATIONRULE
select item;
newPK = Convert.ToInt32(info.Max(p => p.VALIDATIONRULEID)) + 1;
try
{
ODS_VALIDATIONRULE newRule = new ODS_VALIDATIONRULE();
newRule.ALLOWNULLIND = isNull;
newRule.CREATEDATE = DateTime.Now;
newRule.FAILIND = isFail;
newRule.MAXVALUEFACTOR = max;
newRule.MINVALUEFACTOR = min;
newRule.RULEDESCRIPTION = description;
newRule.SOURCESYSTEM = source;
newRule.TABLENAME = table;
newRule.COLUMNNAME = column;
newRule.DATATYPE = datatype;
newRule.VALIDVALUELIST = valid;
newRule.VALIDATIONRULEID = newPK;
entities.AddToODS_VALIDATIONRULE(newRule);
entities.SaveChanges();
insertAccepted = true;
}
catch
{
// Log Error
}
The error I'm getting is this: "An error occurred while preparing the command definition. See the inner exception for details."
Inner Exception: "Operation is not valid due to the current state of the object."
Apparently the issue here was somewhere in the EDMX file and the way it read from Oracle. I deleted the table and recreated it in the DB as well as the EDMX and then added it back. It worked fine then.
The only thing I see that seems odd is you aren't using a sequence for your Pk value. You may try creating one and see if that helps at all.