w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How Entity Framework 5 DbContext manage database connection?
Yes, but it is handled by connection pool so don't worry. Save Changes happens over single open connection for many entities. No, it may be possible but will be difficult to implement it is as very internal and not documented. You can browse source and try, but not worth it, you will hold connections open for long and Connection pool may Suffer from it. We have production Servers with EF4 and we don't see performance issues for nearly 1000 simultaneous requests that peek in a day time.

Categories : Entity Framework

Entity Framework Can't Save in Database
The only way for this error to occur, is for the table to not exist in the database you're connecting to. The connection string you're using for the context cannot be correct. This could occur if the value of the connection string in the Web or App config files is wrong, or you're setting that connection string by hand and setting it wrong.

Categories : C#

Avoiding null or empty values to save in database using Entity Framework
You have several options to fulfill your requirements, two of them are Client Side validation and server side validations that means you need to validate the data before send it to database for saving.. like you have model classes right.. that represent your tables public class User { [Required] public string UserName{get; set;} ... ... } suppose if you try to send null values to controllers or dbcontext it wont allows you to insert null values into it since it allows only non-null values. and also you can do this as well using jquery function buttonClick() { if($('#txtName').val()=='') { alert('Please enter name'); return false; } else { //make ajax call here } } like this you can do it in many ways you can use unobtrusive javascript as well. Hope this helps

Categories : Asp Net Mvc

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, DbContext, SaveChanges() Not Working
Have you tried using Sql Profiler to see if any SQL is being executed against your LocalDB instance? If it is an inconsistency in your model you could enable automatic migrations. There is also a flag you can set against your model indicating whether to allow data loss - AutomaticMigrationDataLossAllowed : Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>()); Automatic migrations

Categories : C#

Entity Framework DbContext in Azure Web Role
You can change Model.Context.tt file, to use CloudConfigurationManager.GetSetting("MyEntities") in place of "name=MyEntities" for MyEntities So each time when context will be re-created, you will always have your changes. In this case you don't need to change anything else.

Categories : Entity Framework

How can I find out what are my EntityValidationErrors when I am using Entity Framework 5 and dbContext?
This is the code that I use: public override int SaveChanges() { this.ApplyRules(); try { base.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); //raise a new exception inserting the current one as the InnerException raise = new InvalidOperationException(message , raise); } } throw raise; } }

Categories : Sql Server

Entity Framework: DbContext and setting the ProviderName
You can get to the ObjectContext through IObjectContextAdapter: ((IObjectContextAdapter)context).ObjectContext DbContext ("context" above) still wraps ObjectContext, so don't worry that you will have a new instance. You can instantiate DbContext using this overload public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) {} for example: public class YourDbContext : DbContext { public YourDbContext() : this(new YourObjectEntities(), dbContextOwnsObjectContext: true) {} } Then you can set your connection string inside of YourObjectEntities: public partial class YourObjectEntities : ObjectContext { public const string ConnectionString = "name=YourEntities"; // Get it from somewhere public YourObjectEntities() : base(ConnectionString, "Your

Categories : Entity Framework

Reloading and Updating using Entity Framework and DBContext
I have the following exampe working in a winforms application The trick is the dset.local private void Form1_Load(object sender, EventArgs e) { var dset = Db.Tasks; // Db is my context. DbSet<Task> qry = dset; qry.Load(); bindingSource1.DataSource =dset.Local.ToBindingList(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Debug.Print(Db.Tasks.Count().ToString()); bindingSource1.EndEdit(); Db.SaveChanges(); }

Categories : C#

Entity framework DbContext update value without query and by foreign key
You can do like that (you probably should have all the test process data): TestProcess pr = new TestProcess(); pr.Id = id; pr.UpdateID = updateID; context.Attach(pr); context.ObjectStateManager.ChangeObjectState(pr, EntityState.Modified); context.SaveChanges();

Categories : C#

Avoiding concurrency issues with DbContext and Entity Framework
This problem is not specific to Entity Framework (although EF certainly also has other limitations around UNIQUE constraints). This is common with any similar server-client model. Since the uniqueness will be enforced by the database server at the time of the request, there is no fool-proof way to know in advance if the constraint will be violated, until you attempt the insert. That said, checking for uniqueness in advance should be a very cheap operation (on SQL Server, a UNIQUE constraint will also give you an index on that column), so depending on how often you expect the application to be attempting duplicate insertion, this should cover the large majority of your cases. But if the duplicate insert attempts would be quite rare to begin with, you can avoid making the extra round-trip p

Categories : Dotnet

Entity Framework 5 - Immediately refresh DbContext after saving changes
The problem is probably due to the fact that the item you are adding to the context is not a proxy with all of the necessary components for lazy loading. Even after calling SaveChanges() the item will not be converted into a proxied instance. I suggest you try using the DbSet.Create() method and copy across all the values from the entity that you receive over the wire: public virtual TObject Create(TObject obj) { var newEntry = this.DbSet.Create(); this.Context.Entry(newEntry).CurrentValues.SetValues(obj); return newEntry; } UPDATE If SetValues() is giving an issue then I suggest you try automapper to transfer the data from the passed in entity to the created proxy before Adding the new proxy instance to the DbSet. Something like this: private bool mapCreated = false; p

Categories : Entity Framework

Entity Framework 5, Code First and Add-Migration Using a Second DbContext Not Working
Multi-tenancy is not supported in EF5 but is supported in EF6 where you can specify a context for which you want to enable migrations for like this: Enable-Migrations -ContextTypeName {NameOfTheContextType} See the migrations multi-tenancy feature spec on the Entity Framework codeplex site.

Categories : Entity Framework

Should I use a partial class for Entity Framework DBContext in another namespace
All partial class code files must reside within the same assembly. Hope that makes the decision easier. The better solution is to create a 3rd project that contains the full definition of DBContext class with all the collection that is referenced from both Daemon project and web project.

Categories : Asp Net Mvc

Entity Framework DbContext: Value cannot be null, parameter name source
You should define properties instead of fields for sets in your context class. So, instead of fields public DbSet<AProduct> AProducts; You should use properties public DbSet<AProduct> AProducts { get; set; } Because Entity Framework looks for properties. If you will explore sources of DbContext class, you will see, that in constructor in searches for declared set properties and initializes them: private void DiscoverAndInitializeSets() { new DbSetDiscoveryService(this).InitializeSets(); } This set discover service looks only for properties: var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance; var properties = from p in this._context.GetType().GetProperties(flags) where (p.GetIndexParameters().Length == 0) && (p

Categories : C#

Entity Framework: Providing both DbContext and ObjectContext APIs in shared assembly
You can't say strictly whether a good or bad idea because there is no such thing, it depends totally on your situation. But i could give you a suggestion, you see DbContext wraps an ObjectContext within it and it calls methods on that ObjectContext to do its job, so in way or another it provides a simplified version of the ObjectContext. Of course, this means you can still access the wrapped ObjectContext instance like this var ctx = ((IObjectContextAdapter)db).ObjectContext; where db is your DbContext subclass, so instead of providing two different APIs which may confuse clients and require more maintenance you can enhance you DbContext subclass with the additional methods you require for performance and those additional methods can leverage the ObjectContext. This way you will have less

Categories : Dotnet

Changing entity framework default connection strings used by DbContext at runtime
One of the constructors of the DbContext class accepts a string, and the string can be the name of a connection string or a connection string. To handle this using IoC you could define an abstraction to a connection string provider, something like this: public interface IConnectionStringProvider { string ConnectionString { get; } } public class MyContext : DbContext { public MyContext(IConnectionStringProvider connectionStringProvider) : base(connectionStringProvider.ConnectionString) { } } public class ConnectionStringProvider : IConnectionStringProvider { public ConnectionStringProvider() { } private string _connectionString = null; public string ConnectionString { get { if (_connectionString == null)

Categories : Entity Framework

How to filter DbContext in a multi-tenant application using Entity Framework with MVC4
I like your approach better than some of the other examples you've provided. Filtering based on the logged-in user should be the most effective way to make sure you're filtering your data appropriately assuming each tenant runs off the same codebase and domain. (If not, you could utilize those to filter as well.) If you're concerned about database performance with filtering tables that don't have a CompanyID you can purposely denormalize your database to include that field in those tables. The reflection approach you cited, although elegant, seems overly complicated and like a lot more overhead than including the CompanyID in your db call (especially since the db call is happening in both instances). EDIT (after comment): As for the rest of it, you seem to have written a lot of excess

Categories : C#

Why are there missing client-side results when using OData options with Entity Framework DBContext?
You don't mix and match QueryableAttribute and ODataQueryOptions<T>. Pick one depending on whether you want manual control over applying the query options (ODataQueryOptions<T>) or make it happen automatically (QueryableAttribute). You have two options, public IEnumerable<USER> Get(ODataQueryOptions<USER> options) { var dbContext = new ATMS.DAL.AtmsContext(); var ret = options.ApplyTo(dbContext.USERS).Cast<USER>(); return ret; } or [Queryable] public IEnumerable<USER> Get(ODataQueryOptions<USER> options) { var dbContext = new ATMS.DAL.AtmsContext(); var ret = dbContext.USERS; return ret; } The reason you are seeing that behavior is that you are applying the query twice, once using ODataQueryOptions<T>.ApplyTo an

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#

how can i save the primary key of a entity in another entity when entity framework is saving
Id is not generated until SaveChanges is called. So for this code to work, you have to rewrite it down like this: DbContext.Entity1.Add(entity1); DbContext.SaveChanges(); var entity2 = new Entity2(); entity2.Entity1Id = entity1.id; DbContext.Entity2.Add(entity2); DbContext.SaveChanges();

Categories : Entity Framework

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 to check if data is already present in database using entity framework
Assuming a DbContext db with a DbSet<Sailor> Sailors, if you don't want to check with the database every time you can create a list of all the IDs: var ids = db.Sailors.Select(x => x.Id).ToList(); And check everything against that object: var exists = ids.Contains(idFromFile);

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

Entity Framework - Source control for database schemes and test data?
Considering that you are using the "Database First" approach, you can (within visual studio) create a "Database Project" from your scheme. Using the database project, you don't need to keep the Sql Managemenet Studio opened to maintain scheme and you can configure deploy including loads of data with pre-deployment and post-deployment scripts. I believe this is a simple, elegant and professional way to solve your problem. The database project improved in Visual Studio 2012. Hope it helps.

Categories : C#

Data reader incompatiable error when Entity Framework model generated from a database
So it was a simple solution in the end, as is usual with the problems you spend hours trying to diagnose! I had changed the database that the class library was connecting to recently, but the testbed web app's connection string had not been updated. So I was sitting there, with a colleague, looking at the code and both of us were saying there was nothing wrong, and it turns out we were right; the incorrect code was in the web app's web.config.

Categories : C#

Making use of a generated entity's class constructor when using Entity Framework Database First
The DbContext class has an event called ObjectMaterialized which you can hook up to ... context.ObjectMaterialized += ObjectContext_OnObjectMaterialized This event handler can apply the default value. private void ObjectContext_OnObjectMaterialized( object sender, ObjectMaterializedEventArgs e) { if (e.Entity is Student) (e.Entity as Student).TimeStamp = <default value>; } You'll need to remember to use context.Set<Student>().Create() when you need a new instance of Student instead of newing up an instance.

Categories : C#

Entity Framework 5 do not save array string
Instead of using an array of strings, you can alternatively use a simple string column with some kind of separator like ';' or '|', anything will do. Just make sure that when you retrieve your data from the database you call the C# String.Split method, passing to it the same separator as parameter. For example: string stringToBePersisted = "First Value|Second Value|Third Value"; string[] stringsRetrieved = columnValue.Split('|');

Categories : C#

why i can't save the current DateTime.Now using Entity Framework
Do not switch the Optmistic Concurrency Updates off you will hide the problem and not fix it. do the following: using (var db = new MyEntities()) { using (var transaction = new TransactionScope()) { var newGroup = new Groups { GroupDate = DateTime.Now, GroupName = "someName" }; db.Groups.Add(newGroup); db.SaveChanges(); transaction.Complete(); } } The different now you are creating the TranscationScope inside the DBContext I hope this will solve your problem.

Categories : C#

Entity Framework - MVC - Converting data types requested from database in Model (POCO objects) into business objects used in the View
Not sure if this is really a question for Stack Overflow (feels too much like "what's your opinion on..."), but since you took the time to type up such a long explanation, I will render my two cents: I think you've over-complicated your design. There's an adage about "the complexity of the solution should not exceed the complexity of the problem," which it feels like you've done (hard to say without specific contextual knowledge of your problem). For what it's worth, the "pattern" I've found to be the best tradeoff between SoC and complexity is this: Data project. Provides programmatic access to the data store (database, XML, etc.). Domain project. Provides implementation of business logic/rules. I also define my DTOs here. UI project. Assuming you're developing a tool for a user to use

Categories : C#

Extra table in database Entity Framework Code First With Database Migrations
We do this with no issues. We do add the table through the migration though so we we can ensure all developers have the same schema. If you want to skip this and go via SQL Management studio then you should have no issued either. Sql(@"CREATE TABLE.....")

Categories : C#

Changing Database Schema in the ASP.NET MVC4 Entity Framework Database First Application
If you're using an ADO.NET entity data model, open up your Model.edmx, right-click anywhere and select Update Model from Database in the context menu. If you've added new tables to the database you'll need to mark the checkbox "Tables" under the Add tab. If you've only modified existing tables, you can just press Finish straight away.

Categories : Asp Net Mvc

MVC4 forms that save to entity framework models
When you send in the model to the view, use something like @using(Html.BeginForm("Index")) { @Html.TexboxFor(x => x.Name) // istead of <input type=text> @Html.TextborFor(x => x.Description) <input type="submit" value="Submit button"/> } to bind the model to the view, which in turn will make it post back when you click the submitt button. In the controller you have something like [HttpPost] public ActionResult Index(CourseViewModel model) // because you'd want to use a // view model and not the entity itself { // check if the model is valid // maybe some more logic db.SaveChanges(); return View(model); }

Categories : Forms

Save NpgsqlPoint (Postgresql Point) With Entity Framework
It looks like NpgsqlPoint makes a PostgreSQL point type. This is not the same as a POINT geometry type used by the PostGIS Extension (e.g., geometry(Point, 4326)). To make a PostGIS geometry, you will need x, y and srid (spatial reference ID; e.g. see http://spatialreference.org/). These can be used with a ST_MakePoint geometry constructor, and ST_SetSRID to establish the spatial reference. For example, here's a parameterized command: SELECT ST_SetSRID(ST_MakePoint(:long:, :lat:), 4326) which assumes a WGS84 coordinate (SRID=4326).

Categories : C#

entity framework - how do i know which property threw exception during save?
You can use DbContext.GetValidationErrors() method to retrieve validation rules break information. Article on MSDN.

Categories : Entity Framework

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

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#

ASP.NET MVC with Entity Framework - Update/Save complex type property
As you mentioned, the problem occurs when more than one quantity has same Unit. To avoid adding same unit multiple time you can check if a unit is already in the db. If it exists then reuse the existing unit. if (q.Id == 0) { var unit=db.Units.FirstOrDefault(u=>u.Id==q.Unit.Id); if(unit!=null) q.Unit=unit; db.Quantities.Add(q); }

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 more than one database
I don't think you can do this in one single model, but its possible to make two DbContext classes and then use the values from one to query the other. You wouldn't be able to use Lazy loading between them, but that's a small price to pay.

Categories : Entity Framework



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