w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Entity Framework returning partially empty dataset
The problem was a bad foreign key definition in the Entity Framework Schema. I'm still not sure why some environments created a working version of the query and one environment created a non working query. I'm going to continue researching but fixing the foreign key definition was the solution.

Categories : C#

Entity Framework 6 with SQL Server 2012 gives System.Data.Entity.Core.ProviderIncompatibleException
Try this. Make sure that the project that your ShoppingCartContext is in, is the start up project or when executing the add-migration command include the parameter -startupprojectname ex. add-migration -startupprojectname yourprojectname

Categories : Sql Server

Database first generation Entity Framework 5 System.Data.Entity vs EntityFramework
The version of System.Data.Entity.dll assembly is the same on both .NET Framework 4 and .NET Framework 4.5. The catch is that only one version can be installed on a machine at the same time so even if you target .NET Framework 4 in your project but run your app on a machine with .NET Framework 4.5 you will effectively run it against .NET Framework 4.5 (and therefore the EF5 version of System.Data.Entity.dll assembly). With regards to EntityFramework.dll - up to the version 6 it was build on top of System.Data.Entity.dll (in EF6 the code from System.Data.Entity.dll and EntityFramework.dll was merged and further evolved). If you used EntityFramework.dll in VS2010 it means that it had to be one of the 4.x versions which were EF4. You could continue to use it even with the EF5 version of Syst

Categories : Entity Framework

Entity Framework 6 RC 1 issue - Could not load type 'System.Data.Entity.Config.SingletonDependencyResolver`1'
I also get an error after updating to RC1 when trying to add mapping classes to the model builder using: modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); Error: {"Method not found: 'System.Data.Entity.ModelConfiguration.Configuration.PrimitivePropertyConfiguration1<System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration> System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration1.Property(System.Linq.Expressions.Expression1<System.Func2>)'."} Rolling back to beta 1 also fixes my issue. Seems like some types have been moved into different namespaces.

Categories : C#

Storing a JSON string in SQL Server and returning with ASP.NET Web API and Entity Framework
I found the answer to my problem, using option #1 (treating the column holding the JSON string as a .NET string type). In the JavaScript/AJAX that calls the Web API webservices, all I needed to do was reference the ImageSizesJSON column using JSON.parse() eg: var imagesJson = JSON.parse(ImageSizesJSON); This converts the escape string of JSON to a JSON object, so that it can be worked with correctly as an object in JavaScript.

Categories : Asp Net

Running inline SQL with Entity Framework 5 and returning tracked Entities
Accoring to this: http://msdn.microsoft.com/en-us/data/jj592907.aspx you want the following: public IEnumerable<T> ExecuteSelect<T>(DbContext context, string table) { IEnumerable<T> entities = context.Set<T>.SqlQuery("SELECT * FROM " + table).ToList(); return entities; } myContext.Cats.Where(c => true) returns IQueriable<Cat> (not DbSet) BUT Your returned set will actually be finalized already (eg you cant add extra bits to your query later) so having it Queriable is misdirecting.

Categories : C#

WCF deployment to azure entity framework methods returning exception
Solved. I made sure MySQL.Data.dll, MySQL.Web.dll, MySQL.Data.Entity.dll, and System.Data.Entity.dll System.Data.Entity.Design System.Data.dll are all being copied local (Copy Local is set to true) Add the following to your web.config file: <system.data> <DbProviderFactories> <clear /> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.4.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data>

Categories : C#

Data Annotations for validate an entity framework entity
Duplicate post to Philosophy : make a partial class and set the data annotations to another class

Categories : C#

Entity Framework 5.x data annotations
1) I don't know why. I just know that Db-first approach doesn't add any data annotations to properties. 2) Indeed creating a separate partial class! Here is an example. Because EF will overwrite and regenerate all POCO classes every time you update your model, any changes (also data annotations) to those classes will be lost...

Categories : Entity Framework

Uploading data with entity framework
I suggest that you alter your code to use the same Context for reading and writing. Having multiple contexts for a single transaction is not a better option than having a Context that's alive for a few minutes.

Categories : C#

how to add a new Many-To-Many table data using entity framework
var group = db.Groups.Find(groupId); if (group != null) { group.Users.Add(user); // add user to existing users db.SaveChanges(); } OR user.Groups.Add(group); // add group to existing groups db.SaveChanges(); If you want to replace users, then just assign new collection: group.Users = new List<User> { user }; db.SaveChanges(); If you want to remove user from it's groups and add this user to other group: var user = db.Users.Find(userId); user.Groups.Clear(); var group = db.Groups.Find(groupId); user.Groups.Add(group); db.SaveChanges(); If you want to remove some users from group: var group = db.Groups.Find(groupId); // get your group var userToRemove = group.Users.Last(); // select user, e.g. last one group.Users.Remove(userToRemove); // remove user from group u

Categories : Entity Framework

Can't get data out using SQL query in Entity Framework
The DbSet.SqlQuery and Database.SqlQuery commands both return entity instances. Your sql query has to return the same columns as your entity. Most probably, your SiteData class contains a Robots column that doesn't exist in your SQL query. You can still use Database.SqlQuery< T > to return your data, provided you specify the return type. The return type doesn't have to be an entity type, just have the same column names as your result set. Assuming db is a DbContext instance, you can write: public class MyResults { public int ID{get;set;} public string DomainUrl {get;set;} } ... var stores = db.Database.SqlQuery<MyResults>(SQL, parameters).ToList();

Categories : C#

Entity Framework HasOptional In Data Annotations
Explicitly specifying the optional relationship should be unnecessary. Entity Framework conventions should detect VirtualTerminalId as the foreign key for the relationship, or you can use the ForeignKey data annotation over the VirtualTerminal navigation property: [ForeignKey("VirtualTerminalId")] public VirtualTerminal VirtualTerminal { get; set; } Because VirtualTerminalId is nullable, Entity Framework will register the relationship as optional. There are good explanations here and here.

Categories : C#

Entity Framework 5 Migrations with Data Migration
In your project, go to the Package Manager windows and: Enable migrations: Enable-Migrations Create migration: Add-Migration Initial Create upgrade/downgrade script: Update-Database In you case you are adding a new table (Color) and two new columns. You have reason, if you start your website the FavoriteColor will be deleted including its data. What you can do: In the package manager console when you run Add-Migration Initial that will create a new script (C# file). As you can see in this file there is one column deleted, 2 added and 1 table created. Make sure the table is created before the columns, populate it with data, create your 2 columns with existing data based on old column and then delete the column. Another way (perhaps better) is to do this in several migration scripts

Categories : C#

Entity Framework not flushing data to the database
Well this could mean that you're not tracking changes, how about you try to set the State to -> Modified and see if it's going to work: var product = products.First(); product.Name = "Shirt"; product.State = EntityState.Modified; context.SaveChanges(); If you want to enable it for the context you can do it like this: context.Configuration.AutoDetectChangesEnabled = true;

Categories : C#

SQL/Entity Framework Group data by hour
Can you try this, visits.Where(u=> u.Start != null).GroupBy(u => u.Start.GetValueOrDefault().Hour).Select(g => new { OnHour = g.Key, Totals = g.Count() }) And Sql Query; SELECT COUNT(*) AS [Totals], [t1].[value] AS [OnHour] FROM ( SELECT DATEPART(Day, COALESCE([t0].[LASTCONNECTIONTIME],'1.1.0001 00:00:00')) AS [value], [t0].[Start] FROM [visits] AS [t0] ) AS [t1] WHERE [t1].[Start] IS NOT NULL GROUP BY [t1].[value]

Categories : SQL

Saving data using Entity Framework 5.0 and xtragrid
You should add the entity to your context, or in case your're performing a update, attach the entity and set the State property to modified: http://www.dotnetcurry.com/ShowArticle.aspx?ID=619

Categories : C#

Entity Framework saving data in one-to-one relation
Have you tried using the .Include() method? I think in your case it would be: this.Table2Objects.Include("Email").ToList(); Or this.Table2Objects.Include(t => t.Email).ToList(); Hopefully that helps.

Categories : C#

Entity framework how to pass data to view?
Typically the Index action is for showing a grid of all the entities (in this case ChatLogs). One of the points of the Razor View Engine is that you get typed Views. So typically I would pass the data to the view directly as opposed to using the ViewBag. public ActionResult Index() { using(var db = new ChatLogContext()) { var list = db.ChatLogs.ToList(); return View(list); } } The next step is to have the View typed to IEnumerable<ChatLog>. Visual Studio should help you with that. Then you can just foreach over the ChatLogs.

Categories : Asp Net Mvc

Entity Framework loads excessive data
It may be because of the virtual keyword. A virtual ICollection will be lazy-loaded. See this SO link.

Categories : Entity Framework

Do I need to reference Entity Framework everywhere I use my Data Context?
I see 2 options here: 1 - Instead of exposing the Entity Framework context in your Model project, create an intermediate layer of abstraction that allows you to query the context indirectly. There are plenty of examples in the web about this. 2 - Separate the Context from the Entities themselves and have the Entities in a common layer throughtout the solution, while the Context lives specifically in the Data Access layer

Categories : C#

Why can't I use the Column data annotation with Entity Framework 5?
Column is in: using System.ComponentModel.DataAnnotations.Schema; the following code: using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace ConsoleApplication2 { public class MyContext : DbContext { public IDbSet<Entity> Entities { get; set; } } public class Entity { public int Id { get; set; } [Column(TypeName = "image")] public byte[] Photo { get; set; } } } produces:

Categories : Visual Studio 2010

The data reader is incompatible with the specified Entity Framework
To me it seems that both branches of the IF return different data, the first branch returns 9 columns where the second - only three. I believe the EF can't reflect the IFramingSystem from the latter. Specifically, the column FrameType (and 5 other columns) are obviously missing: ... SELECT c.ID,c.Name,c.Descr <- where are the remaining columns from Catelog.Component c ...

Categories : C#

entity framework seed data issue
Try this: context.Person.AddOrUpdate(p => new {p.Id}, <yourpersonobject>); context.SaveChanges(); So it can take Id as the unique identifier key. Or in your case: new List<Person> { new Person {Id=1, Name="admin",SurName="admin",Email="admin@admin.com",IdentityNumber="12345678900"}, }.ForEach(a => context.Person.AddOrUpdate(p => new {p.Id}, a)); Should work

Categories : Asp Net Mvc

0..1 to 0..1 relationship in entity-framework by data annotation
You can do something like this: public class Foo { [Key] public int FooId { get; set; } public virtual Bar Bar { get; set; } } public class Bar { [Key] public int BarId { get; set; } public virtual Foo Foo { get; set; } } Hope it helps! Good Luck :)

Categories : Entity Framework

Optimizing Entity Framework Data Call for One to Many
It should help to start with RegionCustomers: EntitiesManager.RegionCustomers.Where(function(regionCustomer) regionCustomer.RegionID = CurrentUserRegionID).SelectMany(function(regionCustomer) regionCustomer.Customers).ToList() I am not used to the VisualBasic syntax, but if that is incorrect, in C# it would be: EntitiesManager.RegionCustomers.Where(regionCustomer => regionCustomer.RegionID == CurrentUserRegionID).SelectMany(regionCustomer => regionCustomer.Customers).ToList(); I think that the SQL will be something along the lines of: SELECT * FROM Customer WHERE CustomerID IN (SELECT CustomerID FROM RegionCustomer WHERE RegionID = {0}) You may also want to consider paging with skip().take() and optimizing the RegionCustomer table with a Foreign Key relationship with Custome

Categories : SQL

No data available with Entity Framework when consumed by second project
I had forgotten that the connection string from the web.config file is only honored when running as a web app. The TCP service .exe needs its own copy of the connection string in App.config. It just happened that the default (implicit) connection string on my TCP service connected to a valid, but empty, copy of my database.

Categories : Entity Framework

Play Framework WS: Returning JSON data as Int
What this message is telling you is that the JSON your providing is not parseable in the type you expect. The first one is about Some(data.value(0).as[JsArray].value(0).as[Int]). apparently data.value(0).as[JsArray].value(0) is not a Number, and therefore can't be converted to an Int. For the second one, val data = (response.json "data").as[JsArray] since the id does not exist, apparently the Json you get has no key 'data', or the value at that key is not an array (null ?). I suggest you log the value of r.json before parsing. You'll see exactly why it's failing. You should also avoid using as and use validate instead (http://www.playframework.com/documentation/2.1.2/ScalaJsonRequests).

Categories : Json

Entity framework move/archive data from one database to another
There is no simple way in EF5 to do this. If your database is MSSQL you can make use of partitioning for archive tables (see http://blogs.msdn.com/b/felixmar/archive/2011/02/14/partitioning-amp-archiving-tables-in-sql-server-part-1-the-basics.aspx for more information).

Categories : C#

How do i insert data already present in one table into another using Entity framework
Assuming you have 2 .edmx files (and therefore different dbcontexts for each database), are you looking for something like this? List<int> userids = new List<int>(); using(var ctx = new TrackUsersEntities()) { userids = ctx.Users.Select(f => f.UserId).ToList(); } using(var ctx2 = new OtherDatabaseEntities()) { foreach(var id in userids) { ctx2.Terms.Add(new Term() { ID = id }); } ctx2.SaveChanges(); } As for where to place the code, I'd put it in the Services layer (if it exists), otherwise in the Controller class.

Categories : Asp Net Mvc

Entity framework large data set, out of memory exception
The issue is that when you get data from EF there are actually two copies of the data created, one which is returned to the user and a second which EF holds onto and uses for change detection (so that it can persist changes to the database). EF holds this second set for the lifetime of the context and its this set thats running you out of memory. You have 2 options to deal with this renew your context each batch Use .AsNoTracking() in your query eg: IEnumerable<IEnumerable<Town>> towns = dbContext.Towns.AsNoTracking().OrderBy(t => t.TownID).Batch(200000); this tells EF not to keep a copy for change detection. You can read a little more about what AsNoTracking does and the performance impacts of this on my blog: http://blog.staticvoid.co.nz/2012/4/2/entity_framework_an

Categories : C#

retrieve data from sqlserver in vb.net using entity framework and native sql
To get all the cars it would be: Using db As New SampleDBEntities Dim cars = db.Cars.ToList End Using To get all cars by type, if you have a 'type' field in that entity. Using db As New SampleDBEntities Dim mazdaCars = db.Cars.Where(Function(c) c.Type = "Mazda").ToList End Using ENtity Framework was built for LINQ and Lambda. Be sure to close/dispose your entity container object.

Categories : Vb.Net

Converting entity framework model to data contract
Cant believe it. Entity framework classes dont need to be taged as [DataContract]. I got error when consuming service with wcf test client, but my wpf client is working great. I am so sorry about that.

Categories : C#

Entity Framework - Blank data is still added to Database
Try using string.IsNullOrEmpty() if (string.IsNullOrEmpty(ins.name == null) || string.IsNullOrEmpty(ins.email == null) || string.IsNullOrEmpty(ins.gender == null) || string.IsNullOrEmpty(ins.password == null)) { Label1.Text = "Incomplete input"; } else { User_save.Users.AddObject(ins); User_save.SaveChanges(); }

Categories : Database

how to insert data into two tables at a time using entity framework
quite simple. Given the case you have a relationship defined between the tables you can do the following: using ( Entity EF = new Entity()){ EF.addToProductTax(new ProductTax(){ Product = new Product(){ pid = //your generated Product id, salePrice = price }, Tax = (FROM t in EF.tax where t.taxid == taxid select t); }); } for easier comprehension: Product item = new Product(); item.salePrice = price; // pid gets generated automatically ! Tax correspondingTax = (from t in EF.tax where t.taxid == taxid select t); Product_Tax add = new Product_Tax; add.Product = item; add.Tax = correspondingTax; EF.addToProductTax(add); Remember, this only works if you have a relationship defined between the two tables. in every other case you wil

Categories : C#

How can I get child data when Lazyloading is not enabled using Entity Framework 5?
You can eager load multiple levels by using .Include() in your DbQuery or explicitly lazy load by calling .Load() on the DbEntityEntry.Collection or DbEntityEntry.Reference. Example context.MyParentEntities.Include(x=>x.ChildEntities); //eager load //explicit collection property lazy load context.Entry(MyEntity).Collection(x=>x.ChildEntities).Load(); //explicit reference property lazy load context.Entry(MyEntity).Reference(x=>x.ChildEntity).Load(); Here is a useful guide : http://msdn.microsoft.com/en-us/data/jj574232

Categories : C#

Entity Framework 5 is sending back the wrong data
What is the proper solution and why does this happen? Simply put, there is no proper solution in your scenario. Refresh is not applicable at all after you have performed a projection (select new) into a type (SummaryModel) that isn't an entity. Your result collection does not contain entities but SummaryModels. You neither can apply Refresh nor Attach to this collection or its elements. Both methods are intended to work with model entities: Refresh updates properties of an already attached entity from the data store and Attach adds an entity to the context in state Unchanged. I suggest that you open a new question and describe why you think that "EF is sending back the wrong data" and try to solve this problem. It's unlikely that re-loading provides correct data when loading delivers

Categories : Vb.Net

Entity Framework data provider not found, entityclient
Right, I figured out the issue. You cannot use that connectionstring for anything else than the edmx connection. The way I have it in my web.config makes the website use that same connectionstring for the membership stuff too, which is not compatible with the System.Data.EntityClient provider and needs the System.Data.Sqlclient in my case. Adding a second connectionstring, minus the Entity Framework stuff in it and having that referenced by the membership provider attributes in the web.config removes all errors and allows the page to render and request stuff from the SQL server. Nightmare over, can return to work on my website. o/

Categories : Entity Framework

ASP.NET MVC 4 with Entity Framework and SimpleMembership linking data between tables
You could generate Configuration classes that inherit from EntityTypeConfiguration, where T is your model class (Account, Student or Classroom in your case). Using the fluent API, you could create the many-to-many relationship, such as many students may have many accounts; the junction table of Student_x_Account could then represent the relationship of STUDENT_ID to ACCOUNT_ID.

Categories : Asp Net Mvc

How to get data as DataSet from stored procedure in Entity Framework
There is no direct conversion. You have to either loop thru result and populated datatable/dataset manually in the loop or use the same connection but in real ADO.NET Command object/Adapter objects to fill Dataset. But you shouldn't really be needing Datasets in EF Project, if you do use EF - use strong types it generates for you.

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.