w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
DBContext in Class Library
Of Course it is possible to use DBContect in a class library, this is what I am currently doing in my projects, I just point them to the DLL(class library) I suspect your app.config file is missing the connection string in the class library project. add it , it should be the same: <connectionStrings> <add name="DBModelEntities" connectionString="metadata=res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.SQLEXPRESS;initial catalog=TEST_DATABASE;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> Don't forget to recompile to see the changes.

Categories : Asp Net Mvc

Proper way to use DBCONTEXT Class in MVC
But my question is that isn't that in this way we are creating Multiple DBConnections. No, don't worry about that. Entity Framework (or more specifically ADO.NET on which it depends) handles actual DB connections in a connection pool. So don't confuse a DbContext with an actual DbConnection. Those are 2 completely different things.

Categories : C#

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

Is it a good idea to wrap my DbContext in a Unit of Work class?
I depends on what you are trying to accomplish. I you want to create an abstraction layer between Entity Framework and your business logic, then yes, it's a good idea. But then you have to do a complete abstraction meaning that your repository classes can not expose IQueryable<T>. If you don't create a complete abstraction, then I do not see any reason to wrap the DbContext in a unit of work class.

Categories : Asp Net Mvc

How could I access special functions baked into a Custom DbContext through a Generic DbContext which lives within a Generic Repository?
It's not clear to me how would you know what function to invoke or what parameters it takes. However you can take a look at the code generated for function imports and it basically looks like this: ((IObjectContextAdapter)this).ObjectContext .ExecuteFunction<Customer>("Customers_With_Recent_Orders", customerId) Therefore (instead of using reflection) you can just do the same thing dynamically - given that even with reflection you would have to know what function to invoke, you should know the type of the entity you expect and you can use params to pass any number of parameters it should be doable. ** EDIT ** You can also execute the function as no tracking by using the other overload: ((IObjectContextAdapter)this).ObjectContext .ExecuteFunction<Customer>(

Categories : Entity Framework

What is difference between dbcontext.Add and dbcontext.AddObject
Actually you are talking about AddObject method of ObjectSet<TEntity> class which was used by old ObjectContext. But since Entity Framework 4 we have DbContext class (which is a wrapper over old ObjectContext). This new class uses DbSet<TEntity> instead of old ObjectSet<TEntity>. New set class has method Add. So, back to differences. Old implementation invoked AddObject method of ObjectContext: public void AddObject(TEntity entity) { Context.AddObject(FullyQualifiedEntitySetName, entity); } New implementation does same thing (see action parameter): public virtual void Add(object entity) { ActOnSet(() => ((InternalSet<TEntity>) this).InternalContext.ObjectContext.AddObject(((InternalSet<TEntity>) this).EntitySetName, entity), Ent

Categories : C#

if i have a static class with a dbcontext field, does that mean the connection stays open for the life of the application?
If you have a static context then it means that all of the resources held by that object will be held for the duration of the application, yes. If you wrap uses of it in a using then you'll simply be using a disposed object after the first call, and it won't work. Instead you should simply create new data contexts at the smaller scope. There isn't a need for it to be a long lived object. Connection pooling helps to ensure that the cost of creating several short lived contexts isn't much more expensive than one long lived context. Have each context represent one logical operation, and then make a new one for the next operation.

Categories : C#

how to get next Identity not the last inserted identity of Identity column
You don't need to do anything to "lock" an IDENTITY value. As soon as the table uses a value of an IDENTITY, it's used forever, even if you do a rollback. SQL Fiddle example: http://sqlfiddle.com/#!3/5fdb9/1/0. Note the ids that make it into the table, only 1 and 5. If that doesn't address your problem, please revise your question.

Categories : Sql Server

How can I use User.Identity.Name to work in a class outside of a Controller?
According to the reflected code, the HttpContext.Current.User is set during the windows authentication OnAuthenticate event. // System.Web.Security.WindowsAuthenticationModule private void OnAuthenticate(WindowsAuthenticationEventArgs e) { if (this._eventHandler != null) { this._eventHandler(this, e); } if (e.Context.User == null) { if (e.User != null) { e.Context.User = e.User; return; } if (e.Identity == WindowsAuthenticationModule.AnonymousIdentity) { e.Context.SetPrincipalNoDemand(WindowsAuthenticationModule.AnonymousPrincipal, false); return; } e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false); } } May need to check whether on

Categories : Asp Net Mvc

Finding out the current Identity Provider in Windows Identity Foundation
You typically use the Issuer and OriginalIssuer properties in each claim that you get. If you use e-mail as the unique identifier: var u = this.User as IClaimsPrincipal; var c = (u.Identity as IClaimsIdentity) .Claims .First( c => c.ClaimType == ClaimTypes.Email ); var issuer = c.Issuer; var originalIssuer = c.OriginalIssuer;

Categories : C#

Where is Microsoft.AspNet.Identity.Owin.AuthenticationManager in Asp.Net Identity RTM version?
That class is gone, as it was basically just adding methods that generated a ClaimsIdentity and passed that into an Owin.Security.IAuthenticationManager. Instead the RTM templates have a SignIn method in the controller that looks something like this: private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }

Categories : Asp Net

How to Alter a table for Identity Specification is identity SQL Server
You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY: ALTER TABLE ProductInProduct ADD NewId INT IDENTITY (1, 1); Update: OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

Categories : SQL

How to disable identity from the existing column & after adding data , how to enable identity again on the same column in SQL Server 2008?
Use SET IDENTITY_INSERT (http://msdn.microsoft.com/en-us/library/ms188059.aspx). SET IDENTITY_INSERT TableName ON; -- Insert Data. SET IDENTITY_INSERT TableName OFF;

Categories : Sql Server

How to map identity provider claim value to/from identity provider registered in Azure ACS?
I tried to do this last week and couldn't find a way to match the value in the claim to the value in IdentityProvider.js. I landed up looking for specific values. The only thing I can suggest is some resource/code that understands the mapping. I was just looking for a specific one and landed up doing something like this: return (HttpContext.User.Identity as System.Security.Claims.ClaimsIdentity).Claims .First(x => x.Type == "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider").Value .Contains("Google") I searched high and low for the data, but couldn't find it. If you do, please submit an answer, I would also like to know

Categories : Azure

Undo DbContext.Add()
You can make use of the explicit implementation of DbContext.IObjectContextAdapter.ObjectContext to get to the underlying ObjectContext and Detach your entity, something like; ((IObjectContextAdapter)_db).ObjectContext.Detach(article); A syntactically cleaner way would be to extend your DbContext with a method; public class MyDbContext : DbContext { public void Detach(object entity) { ObjectContext.Detach(entity); } } ...which would allow you to simply do; _db.Detach(article);

Categories : C#

Use DbContext in repository
You definitely can do that - you can provide protected DbContext from base repository. But I don't think that accessing other repositories from repository is a very good idea. It's better to place such operation (which uses several repositories) into domain service.

Categories : C#

DbContext has been disposed
Your context has been disposed somewhere else (not in the code you've shown), so basically when you access it from your Register action, it throws the exception. Actually, you shouldn't use a static singleton to access to your context. Do instantiate a new DbContext instance for each request. See c# working with Entity Framework in a multi threaded server

Categories : C#

What does it mean when your DBContext is disposed?
What does it mean? It means that you can't continue using your DBContext object. DBContext implements IDisposable; so, it has a Dispose() method which: Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. So, Why was it disposed? Dispose() was called explicitly by something, somewhere or it was called implicitly upon exiting a using block.

Categories : C#

Do I need a DbContext for each database?
This is actually pretty easy to do public class MyContext : DbContext{ public MyContext(string connectionStringName): base(connectionStringName){} } or public class MyContext : DbContext{ public MyContext(DbConnection connection): base(connection, contextOwnsConnection: true){} }

Categories : Entity Framework

Get DbContext from within Entity
I think what you are trying to do, indicates an OO design flaw. It shouldn't be the Entity classes' responsibility to update the database. That's the responsibility of the DBContext. So No, it is not possible, and Wanting to do it, indicates a design flaw (probably) If you want to execute custom SQL, you should execute it from the caller, on the context, not from within the entity itself. An example can be found here: DBContext Native SQL Queries.

Categories : Dotnet

How do I Refresh DbContext
I checked this and id works fine: //Search Box box = dbContext.Boxes.FirstOrDefault(x => x.BoxId == 45); //breakpoint here, change Name of Box by sql management studio //Refresh var context = ((IObjectContextAdapter)dbContext).ObjectContext; context.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, box); //Check refresh and if it is in context box = dbContext.Boxes.FirstOrDefault(x => x.BoxId == 45); Are you sure it is the same db-context?

Categories : C#

Format the dbcontext sql query
If you're sure there is only one result I'd say you could do double Mass = dbMTG.MountingSpecs .SqlQuery<double>("SELECT DISTINCT Mass WHERE Class == 3") .First();

Categories : C#

EF DbContext. How to avoid caching?
You can use the AsNoTracking method on your query. var res = (from b in ctx.Buildings.Where(x => x.ID == 1) select new { b, flats = from f in b.Flats select new { f, people = from p in f.People where p.Archived == false select p } }).AsNoTracking().AsEnumerabe().Select(x => x.b).Single(); I also want to note that your AsEnumerable is probably doing more harm than good. If you remove it, the Select(x => x.b) will be translated to SQL. As is, you are selecting everything, then throwing away everything but x.b in memory.

Categories : Entity Framework

Generic access to DbContext
have a look at this tip that I posted a while ago Anyway the trick is by using context.Set<> public interface IEntity { int Id { get; set; } } public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity { private IDbContext _context; public Repository(IDbContext context) { _context = context; } private IDbSet<TEntity> DbSet { get { return _context.Set<TEntity>(); } } public IQueryable<TEntity> GetAll() { return DbSet.AsQueryable(); } public void Delete(TEntity entity) { DbSet.Remove(entity);

Categories : C#

I have a POCO, can I get a proxy from the DbContext?
Something along the lines of this code will do what you need. I've used automapper to copy values from the passed in entity to the proxied version. The code checks whether the passed in entity is a proxy or not and handles it accordingly. public class Repository<T> where T : class { private readonly Context context; private bool mapCreated = false; public Repository(Context context) { this.context = context; } protected virtual T InsertOrUpdate(T e, int id) { T instance = context.Set<T>().Create(); if (e.GetType().Equals(instance.GetType())) instance = e; else { if (!mapCreated) { Mapper.CreateMap(e.GetType(), instance.GetType()); mapCreated

Categories : C#

NullReferenceException in DbContext.saveChanges()
Problem solved. The cause was a bit silly. I was using the default ASP.NET Web Forms Application project from VS Web Express to perform my testing. This project contains a web form called Contact.aspx, so it already includes a partial class Contact in the same namespace as my Contact entity. Understandably, this didn't play well with Entity Framework, leading to the rather obscure error above. Deleting the aspx page solved the problem.

Categories : C#

DbContext disposed error
You need to give some more information on the model object. Where is it created? Try something like this. using(var context = new DataModel()) { //Prepare your Model var model = RecordsRepository.GetQueryableObject(); //Call LoadRecords return LoadRecords(model); }

Categories : C#

How to empty an EntityFramework DbContext?
I was able to solve it by using reflection in a very sophisticated way. It looks strange but due to the fact that C# does not support a generic wildcard like Java<?> does we need a generic method and call it by reflection. Sure the solution performs slow, but its fast enough for local tests, debugging and development issues. public static void GenericRemoveSet<T>(System.Data.Entity.DbSet<T> set) where T:class { foreach (var item in set) set.Remove(item); } public static void ClearGenericDbContext(DbContext context) { var removeMethod = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.GetMethod("GenericRemoveSet"); foreach (var prop in context.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType &am

Categories : C#

Is it possible to SELECT FOR UPDATE on DBContext?
You cannot do it with one SQL satement, the FOR UPDATE statement you mentioned only lock rows the FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being modified or deleted by other transactions until the current transaction ends. That is, other transactions that attempt UPDATE, DELETE, or SELECT FOR UPDATE of these rows will be blocked until the current transaction ends reference If you want to use the plain SQL on dbContext you can do this for queries without results: string myUpdateSQL = @"UPDATE Table SET Table.col1 = other_table.col1, Table.col2 = other_table.col2 FROM Table INNER JOIN other_table ON Table.id = other_table.id"; using (var context =

Categories : C#

Using DBContext to Select Fields
If you don't want the entire table, then don't just call ToList() on the DbSet, as that will just grab all of the table as you have seen.. You had it right when using Select, since the Select statement is meant to create a projection from one set of data into a new form (new class, model, anonymous object).

Categories : Asp Net Mvc

Why use EF 5.X DbContext Generator when Edmx does the same job?
When you add the new "ADO .NET Entity Data Model", apart from creating the EDMX it also creates the DbContext for you, it's "AdventureWorks_DataEntities". So, you don't need to add a "EF 5.X DBcontext Generator", this already exists in your project. If in Visual Studio you click on the arrow on the left of your .edmx file to unfold it, you'll see several files. Two of them will end in ".tt". These are T4 templates, which are in charge of generating the model entities and the DbContext automatically when you modify the EDMX. Hope this clarifies the concepts, to answer your questions directly: Question 1: You only need step 1, "AdventureWorks_DataEntities" is your DbContext. If you open the "AdventureWorks_DataEntities.cs" file you'll see this class inherits from DbContext. Question 2: T

Categories : C#

Add object graph to DbContext
You have to generate your id, put this annotation above the ID [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] for more info see this related question

Categories : C#

MVC DBContext, how to connect to a table?
public EquipmentDBContext() : base("name=ITAPPConnectionString")//this name should be the name of database { } public DbSet<Equipment> Equipments { get; set; } here you say you have a Datamodoel called Equipment. Your context also defines a single property, Equipments, which is of type DbSet. This property acts as a collection that allows you to query the data in you table in database as though it were an in-memory collection of objects. So, if you create an object of class EquipmentDbContext in controller named lets say db, then you can access the data in table with something like db.Equipments

Categories : SQL

How to implement DbContext hiearchy
As I mentioned here: EF6 Empty Model target string I began this effort using Rowan Miller's example here: http://romiller.com/2013/02/15/extending-and-customizing-code-first-models-part-2-of-2/ In the end, I abandoned that approach, for a few reasons: 1) I couldn't get it to work (I can't remember exactly why but I do suspect it was related to differences in EF since the article was written), and 2) I didn't like the need to write manual migrations. I ended up with PluginContexts that inherit from HostContext, as I had hoped, and am able to reference and even inherit from host entities. This has restrictions in its use though: My plugin logic is completely self contained. I have no need for the host application to manipulate or create plugin entities. Therefore, I am not trying to g

Categories : Entity Framework

Why has EntityFramework generated a DbContext?
You need a context in order to use Entity Framework. You can either write one yourself or you can use the tool to automatically generate it. With newer versions of EF using database first (.EDMX and designer) it will automatically generate a DbContext for you. The DbContext you showed above is NOT a "Code First" context as it has the UnintentionalCodeFirstException. If that exception is being thrown then it suggest you are trying to use code first mode. Check the database exists and check the connection strings. Don't use code first by mistake.

Categories : Entity Framework

Execution of non-generic DbContext.Set?
I should have deleted my question since the answer is too simple, but for the record, let's just keep it up. namespace System.Linq { public static class EntityFrameworkExtensions { public static IEnumerable<object> AsEnumerable(this DbSet set) { foreach (var entity in set) yield return entity; } } } Usage: var collection = context.Set(entityType).AsEnumerable(); Beware that any filtering performed on the retuned collection will not happen on the SQL server, but on the collection enumerator, the entire table will be returned. Use only when loading all rows anyway.

Categories : Entity Framework

How to best utilize DBContext with a Web API application
DbContext is not thread-safe, so making it static is not a good thing for server code. The overhead of creating a DbContext is low so I do not see why we have to avoid making it instance variable.

Categories : C#

eSQL queries on DbContext/EF6
I solved this by creating a T4 file that adds to the main context (query on tables) and to all entities (navigation/foreign key). Here is the simplified version: // Get table as ObjectQuery var myGarden = ((IObjectContextAdapter)this).ObjectContext.CreateObjectSet<Garden>("Gardens").First(); // myGarden is ObjectQuery with eSQL support var foo = myGarden.Where("it.Works = true"); // Get the Flowers (navigation) from the Garden entity as ObjectQuery var flowers = (ObjectQuery<Flower>)Entry(myGarden).Collection<Flower>("Flowers").Query(); // flowers is ObjectQuery with eSQL support flowers.Where("it.AlsoWorks = true");

Categories : C#

Error multiple objects with the same key DbContext
If you load the entity from the context you cannot attach an entity with the same key agai.See this question or this public override void Update(T entity) where T : IEntity { if (entity == null) { throw new ArgumentException("Cannot add a null entity."); } var entry = _context.Entry<T>(entity); if (entry.State == EntityState.Detached) { var set = _context.Set<T>(); T attachedEntity = set.Find(entity.Id); // You need to have access to key if (attachedEntity != null) { var attachedEntry = _context.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(entity); } else { entry.State = EntityState.Modified; // This should attach entity } } enter code here }

Categories : C#

What is the point of DbContext proxy objects?
EF uses proxy objects to track changes dynamically and to use lazy loading. When we have defined a property as virtual EF can override it to support these behaviors. We need lazy loading to load navigation properties whenever we access it Dynamic change tracking , If we do some change on a property the proxy will notify that to the change tracker immediately. If we do not use dynamic change tracking change tracker needs to go through all the properties before save changes , to discover changes. So try doing this, alert.Title = "Changed title"; context.DetectChanges();

Categories : Dotnet



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