logo
down
shadow

What is difference between dbcontext.Add and dbcontext.AddObject


What is difference between dbcontext.Add and dbcontext.AddObject

Content Index :

What is difference between dbcontext.Add and dbcontext.AddObject
Tag : chash , By : Mihai Mocanu
Date : December 01 2020, 04:55 PM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Equivalent of ObjectContext.AddObject(entityName, entity) on DbContext


Tag : chash , By : Shrek Qian
Date : March 29 2020, 07:55 AM
it should still fix some issue With DbContext you can use context.Set().Add(entity);
Example: context.Set() is equivalent to context.Users so context.Set().Add(myUser) is equivalent to context.Users.Add(myUser).
protected void SaveEntity<T>(T entity)
    where T : class
{
    using (DocsManagerContainer context = new DocsManagerContainer())  
    {  
        DbTransaction transaction = null;  
        try  
        {  
            context.Connection.Open();  
            transaction = context.Connection.BeginTransaction();  
            context.Set<T>().Add(entity);  
            transaction.Commit();  
            context.SaveChanges();  
        }  
        finally  
        {  
            context.Connection.Close();  
                transaction = null;  
        }
    }
}

Dependancy Injected DbContext is empty after populating DbContext created with new (EF7, ASP.NET 5, vnext)


Tag : asp.net , By : tlync
Date : March 29 2020, 07:55 AM
Does that help I might be wrong, but my assumption is that when you create a new instance of DbContext in code, you are using the parameterless constructor that sets underlying connection string to some default value. However, DI-injected DbContext could be resolved using another constructor with different connection string passed in explicitly.
That's an example of Unity config that explicitly specifies constructor parameter:
<register type="DbContext, [assembly-name]" mapTo="DbContext, [assembly-name]">
<constructor>
    <param name="nameOrConnectionString" value="Test"/>
</constructor>
</register>

EF Core - Disposable DbContext and Attach() - or - DbContext as member - or - Disconnected Entities


Tag : chash , By : Franky
Date : March 29 2020, 07:55 AM
I hope this helps . Side Note:
in MVVM ObservableCollection.CollectionChanged is supposed to inform View about changes in Model, resp ViewModel. I would not recommend to let View modify ObservableCollection and then use CollectionChanged to reflect the changes in ViewModel. Try to keep ViewModel -> View notification flow, not the other direction.* Every change is done in ViewModel and reflected in the View.
public class YourPageViewModel
{
    private readonly ObservableCollection<VendorItemVm> _deletedVendors = new ObservableCollection<VendorItemVm>();
    public List<VendorItemVm> Vendors { get; } = new List<VendorItemVm>();

    void Add()
    {
        Vendors.Add(new VendorItemVm
        {
            IsNew = true,
            Id = new Guid(),
            UserName = "New Vendor",
        });
    }

    void Remove(VendorItemVm vendor)
    {
        Vendors.Remove(vendor);
        _deletedVendors.Add(vendor); 
    }

    async Task Load()
    {
        using(var db = new DbContext())
        {
            var vendors = db.Vendors.AsNoTracking().ToList();
            foreach(var entity in vendors)
            {
                Vendors.Add(new VendorItemVm
                {
                    Id = entity.Id,
                    Name = entity.Name,
                });
            }
        }
    }

    async Task Save()
    {
        using (var db = new DbContext())
        {
            //convert viewmodels to entities
            var newVendorsEntities = Vendors
                .Where(v => v.IsNew)
                .Select(v => new Vendor
                {
                    Id = v.Id,
                    UserName = v.UserName,
                    TimeSpan = DateTime.Now,
                })
                .ToArray();

            //add new entities
            foreach (var vm in Vendors.Where(v => v.IsNew))
            {
                var entity = new Vendor
                {
                    Id = vm.Id,
                    UserName = vm.UserName,
                    TimeSpan = DateTime.Now,
                };
                db.Vendors.Add(vendor);
            }

            //delete removed entities:
            foreach(var vm in _deletedVendors)
            {
                var entity = new Vendor { Id = vm.Id };
                db.Vendors.Attach(entity);
                db.Ventors.Remove(entity);
                db.Vendors.Add(vendor);
            }

            await db.SaveChangesAsync();

            //reset change tracking
            foreach (var vm in Vendors) vm.IsNew = false;
            _deletedVendors.Clear();
        }
    }
}
public class YourPageViewModel
{
    MyDbContext _myUoW;
    public ObservableCollection<Vendor> Vendors { get; } = new ObservableCollection<Vendor>();

    void Add()
    {
        var entity = new Vendor
        {
            Id = new Guid(),
            UserName = "New Vendor",
        };
        Vendors.Add(entity)
        _myUoW.Vendors.Add(entity);
    }

    void Remove(VendorItemVm vendor)
    {
        Vendors.Remove(vendor);
        _myUoW.Vendors.Attach(entity);
        _myUoW.Vendors.Add(entity);
    }

    async Task Load()
    {
        using(var db = new MyDbContext())
        {
            Vendors = db.Vendors.AsNoTracking.ToList();
            foreach(var entity in vendors) Vendors.Add(entity);
        }
        _myUoW = new MyDbContext();
        //if you want to track also changes to each vendor entity, use _myUoW to select the entities, so they will be tracked. 
        //In that case you don't need to attach it to remove
    }

    async Task Save()
    {
        //add new entities and delete removed entities
        _myUoW.SaveChanges();

        //reset change tracking
        _myUoW.Dispose();
        _myUoW = new MyDbContext();
    }
}

More than one DbContext named 'NewProject.Models.DbContext' was found Specify which one to use by providing its fully qu


Tag : chash , By : user105769
Date : March 29 2020, 07:55 AM
I hope this helps . I'm leaving that question and answer here so people don't go crazy looking for all possible solutions manually like I did. I found out that adding the context in the Configure method of IdentityHostingStartup.cs was causing the problem. I changed the place where I added the context to the Configure method of Startup.cs and it was working just fine.
namespace ShareAndCare
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });            

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<ShareAndCareContext>(options =>
                   options.UseLazyLoadingProxies().UseSqlServer(
                       Configuration.GetConnectionString("ShareAndCareContextConnection")));

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });                
        }   
    }
}

Create a new DbContext or use the injected DbContext when calling a stored procedure in Entity Core?


Tag : chash , By : Mihai Mocanu
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • "The attribute names could not be inferred from bind attribute 'bind-value'" exception in Blazor
  • How to fix ''System.ArgumentException" in c#?
  • C#. Ref returning delegate for ref extension method
  • Swashbuckle Swagger generate an actual guid
  • Trying to make thousands of database calls simultaneously - they stack instead of running concurently
  • run mstest from cmd using testcontainer
  • How to make M:N (many-to-many) relationship where both M and N are the same entities?
  • Consume COM DLL from multiple clients
  • Convert json string response representing UCHAR array to Byte array
  • Why does this LinqPad program produce different results on the second run?
  • ServiceStack how to use MaxLoginAttempts feature
  • What does "late-bound access to the destination object" mean?
  • How to load appsettings.json inside a Static class based on deploy environment so that I can use in other class librarie
  • dynamically add images to view
  • Are static extension methods on User object safe?
  • Process thousands of database calls simultaneously
  • Trying to decrypt a string with public key(not private) using bouncycastle in .net
  • How to retrieve the name of an usb device
  • Query many-to-many related data using Entity Framework Core
  • ASP.NET MVC : how to find the view from a controller?
  • Inconsistent behaviour using Entity Framework for ASP.NET MVC app vs windows service
  • AutoFixture Customize vs Build
  • How to change textbox location at the click of a mouse in live mode?
  • How can I deserialize a XML file without defining the parent node?
  • asp.net core how decrease class coupling
  • ASP.NET Core Razor Pages Routing With parameters
  • String Escaping With $ Interpolation and @ Encoding
  • ConfigurationManager in ASP.NET WebAPI tested with HttpServer
  • Top down shooting in Unity 2D don't work as I want it to
  • Use own redirectUri when the Authentication expires
  • Using "foreach" in string array c#
  • "Object reference not set to an instance of an object" for create multiply models on one view
  • Get data passed trought pushAsync
  • Selector expression dynamic on IQueryable
  • Logut with SignInManager not calling method
  • Exit event handler with MessageBox OK button
  • Can not load view from Custom Renderer Xamarin Forms
  • Looking for a .Net ORM
  • Cost of SortedDictionary.Count
  • All possible combinations of n items selected randomly from a set of x items (algorithm)
  • Displaying process percentage on DOS screen
  • C# Importing Large Volume of Data from CSV to Database
  • c# control location precision
  • Printing to Zebra printer gives faint and blurry images
  • How to avoid stepping into dll code file?
  • Programmaticaly prevent Vista desktop search (WDS) from indexing pst files placed on mapped network drives
  • Is there anyway to reduce IsolatedStorage capacity in Silverlight?
  • C#: How to print a unicode string to console?
  • Frequency Table with Random Values
  • My Visual Studio 2008 web application keeps throwing a .Net error when I first run it, but refreshing fixes it
  • TCP Connection Creation and Closing Event Hooking
  • Find changed properties of a class
  • C#: Object with custom marshaller not containing data after PInvoke call
  • Version Control System with API. Need to get metrics
  • Performance comparison of Dictionaries
  • How to get process name and title of the top window on Windows / C#
  • How to save the ListView contents to a text file?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com