Menu
  • HOME
  • TAGS

SQLite.net Extensions loads the same entity multiple times rather than returning the same reference

entity-framework,entity-framework-7,sqlite-net-extensions

You are correct, SQLite-Net Extensions caches the objects for recursive calls to avoid reference loops and handle inverse relationships, but it doesn't cache the objects between calls. SQLite-Net Extensions is just a thin layer over SQLite.Net, if integral reference is important for you, you can go back to manual queries...

Distribute entity framework models over different assemblies

c#,.net,entity-framework,model,entity-framework-6

You can search for your models in every assembly over reflection. Iterate through the AppDomain's assemblies and search for an attribute, interface or base class, see an example below. protected override void OnModelCreating(DbModelBuilder modelBuilder) { var entityMethod = typeof(DbModelBuilder).GetMethod("Entity"); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var entityTypes = assembly .GetTypes()...

When are Entity instances automatically attached to a context?

c#,entity-framework

As you saw, the problem is that your Navigational properties are from another context(They are tracked by another context). These Objects are tracked by another context. When you call the Add method EF not only adds that object as Added but also all its Navigational properties/Associations You can 1)Pass the...

Downside of using transaction dispose with entity framework integration testing

entity-framework,transactions,entity-framework-6.1

as the database is never touched Surely it's touched. Everything that happens within the transaction happens in the database. Identity values and sequences (if any) are incremented, triggers fire, referential constraints are checked, etc. etc. The only thing is, it happens in isolation and in the end everything (except...

Methods defined in an interface can no be used from another class

c#,entity-framework,interface

Your definition public abstract class EntityDao<IEntity> : IDao<IEntity> defines a type parameter named IEntity that hides the interface named IEntity that you defined elsewhere. In order to avoid confusion, John (Saunders, in his now-deleted answer) rightly advises using a standard naming convention that eliminates this kind of name conflict: Prefix...

C# entity framework MVC second run error

entity-framework,asp.net-mvc-4,localdb

Your initialiser is using the DropCreateDatabaseAlways class which, as it suggests, drops that database every time the application is initialised. Instead perhaps you could use CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges: public class ComponentDbInitialize : CreateDatabaseIfNotExists<ComputerContext> { } ...

Related entity not loaded

c#,.net,entity-framework

Mark your relation property with virtual keyword for EF's proxy to be able to overload it: [ForeignKey("SchoolClassId")] public virtual SchoolClass SchoolClass { get; set; } Also, be sure that context's DbContext.Configuration.ProxyCreationEnabled property value is set to true (by default it is). These two conditions enabling lazy loading of your relations....

ASP.NET EF6 - 2 Tables & 1 Link Table

c#,sql-server,asp.net-mvc,entity-framework

If you are looking to add an employee and their contact info on the same form, then you should use a View Model. Your View Model will be an amalgamation of the properties you need on both the Employee and Contact into one class. You will then implement your Employee...

sqlite query slow, how to optimize (using linq to entities)

c#,linq,entity-framework,sqlite

The biggest optimization would be changing the Contains to a StartsWith. Which would be equivalent to changing from name like '%search%' to name like 'search%'. Otherwise SQLite can't fully use the indexes you placed on the columns and you are basically searching the whole table. // First Name if (!string.IsNullOrEmpty(firstName))...

Difference between cast and as inside a select in LINQ

c#,linq,entity-framework

LINQ to Entities is not the same as LINQ to Objects. While LINQ to Objects functions can take any matching delegate and blindly invoke it as normal C# code, LINQ to Entities treats your lambdas as expression trees because it needs to understand the semantics of those lambdas (not just...

Entity Framework connection factory not working

c#,entity-framework,connection,entity-framework-6,sqlanywhere

It is important that the configuration section in the app.config does not exists, because it has a higher priority.

entity framework validation context - null exception in null test

c#,entity-framework

CPU seems to be treated by the entity framework as a navigation property. Without more information this suggests that you'll need to: using System.Data.Entity in whatever unit selects the model .Include(c => c.CPU) before enumerating the query from the database If that's truly a navigation property, as it appears, it...

How to use Join and Where to return an IList?

c#,linq,entity-framework

public IList<Promotion> GetRewardsForUser(string userId) { //a list of all available promotions IList<Promotion> promos = _promotionLogic.Retrieve(); //contains a list of Promotion.objectIds for that user IList<PromotionsClaimed> promosClaimed = _promotionsClaimedLogic.RetrieveByCriteria(t => t.userId == userId); //should return a list of the Promotion name and code for the rewards claimed by user, but a...

How to avoid async/await deadlock when blocking is required

entity-framework

This is the classic ASP.NET await deadlock. You have been calling Wait or Result somewhere. Don't do that. If you must block (which you have indicated) block in a safe way: Task.Run(anything).Result. Don't modify all sites where you await. If you miss one you deadlock (potentially non-deterministically at 4AM in...

Viewmodel binding for Edit View

c#,entity-framework,mvvm

I believe you're on the right track with POST. GET is much more simplier: public ActionResult Create() { return View(new ContactsCreateViewModel() { ... your initial settings, may be contained within constructor of view model directly ... }); } The GET request requests server to provide empty form, which is filled...

A specified Include path is not valid. The EntityType '*Propiedad' does not declare a navigation property with the name 'Nombre'

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,repository-pattern

Include is made to eagerly load navigation properties, meaning any property that is, in fact, another related entity. Since Nombre is a string, you do not need to include it: it is part of the entity that is returned from the database call. If Nombre were of a class representing...

Linq where on include

c#,linq,entity-framework

If you have database relationship properly configured this have to work. tableA.Include(x => x.tableBChilds).Where(tableA => tableA.tableBChilds.Any(b => b.R== 1)).ToList(); ...

How to assign list to generic list

c#,entity-framework

You don't, because the list that you haven't isn't the same type as that generic type. You should be returning a list of the type of the values you actually have. public List<State> GetApprovedStateList(DateTime effectiveDate) { using ( var db = new Context()) { return (from a in db.StateProductList join...

Select query in Entity framwork

entity-framework

Firstly you must add static to Users like this: public class ChatContext : DbContext { public static DbSet<User> Users { get; set; } public DbSet<Conversation> Conversations { get; set; } } Secondly you must add FirstOrDefault method to your query, because it will return an iQueryable like this: var newtext...

How to make LINQ to multiple tables

c#,asp.net,linq,entity-framework,code-first

With LINQ ORMs you generally try to avoid joins and use navigation properties directly. You write it as if the objects were in memory and connected by regular object references and collections: clients.Clients.Where(i => !i.Benefits.Any()) Or, less nicely and slower on SQL Server: clients.Clients.Where(i => i.Benefits.Count() == 0) Note, that...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5

You need to model your collection items. You could go many to many or one to many. // many to many public class Interest { public int InterestId { get; set; } public string InterestDesc { get; set; } // field can't match class name } // one to many...

Avoid EF update the null image to database in .Net MVC

asp.net-mvc,entity-framework,null,edit,httppostedfilebase

Mark Image property as not modified: db.Entry(sach).State = EntityState.Modified; if (image == null) db.Entry(sach).Property(m => m.Image).IsModified = false; db.SaveChanges(); ...

EF Intersect Syntax

c#,entity-framework,linq-to-entities

You can do this in one statement: var nodes = _DbContext.Nodes .Where(n => n.Tags.All(t => tags.Contains(t.DisplayName))); Your statement is not correct because dbTags is a local list containing Tag objects. When you use this list in a LINQ-to-Entities expression there is no way to translate these objects into SQL variables....

Two equal pieces of code work differently

c#,asp.net,asp.net-mvc,entity-framework

I guess the problem is in the fact that you're trying to bind Assignment ID and AssignmentType ID using the same name. Create an AssignmentViewModel class (which is anyway a good practice), where you'll have only the ID of member "type" like this: public class AssigmentViewModel { public int ID...

EF Migrations - should an initial migration be automatically generated?

entity-framework,code-first-migrations

You should look this link. You need to run these two commands: Run the Add-Migration InitialCreate –IgnoreChanges command in Package Manager Console. This creates an empty migration with the current model as a snapshot. Run the Update-Database command in Package Manager Console. This will apply the InitialCreate migration to the...

Foreign key not updating in entity frame work

c#,.net,entity-framework,foreign-keys

Base on Entity Framework does not update Foreign Key object I created public string ModifiedBy { get; set; } [DataMember] [ForeignKey("ModifiedBy")] public User ModifiedUser { get; set; } That means I additionally introduced a primitive type(string ModifiedBy ) for Modified User and specified ForeignKey. That resolved my issue...

how to use where with list of string

c#,entity-framework,ef-code-first

Try this: var SearchList= new List<string>{"one" , "two" , "three" }; var result = dataContext.SourceList.Where(p => p.Tags.Any(t => SearchList.Contains(t.TagName))); Contains will be translated to IN statement...

Entity Framework, Code First, Update independent association (Collection)

c#,entity-framework,collections,ef-code-first

sounds like s is not attached to the dbcontext you should have s = ctx.Set<School>().Where(x => x.Id == 1).First(); Please notice that 1 is a hardcoded value, you should have a variable valued according to the application context. Please also notice that if the suggestion of Jan is not the...

Entity Framework + Boolean Matrix

c#,asp.net,entity-framework

The reason your public bool?[] columns { get; set }; doesn't work is simple. It needs to be changed to this. public bool?[] columns { get; set; } The reason is the ; was misplaced....

Entity Framework query return my primary key plus $id

c#,json,asp.net-mvc,entity-framework,linq-to-sql

use this to configure the json serializer var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; ...

LINQ to SQL: How to create something like conditional include?

.net,linq,entity-framework,include,condition

If you are only trying to get the events where userID ==1, you can use the following. This will give you only the event you need from the Event Collection for the user. User u = new User() { UserId = 60 }; Event e1 = new Event() { EventId...

Entity Framework Invalid Column (Column Does Not Exist in Database or Code)

c#,.net,entity-framework

This is not an Entity Framework problem. It's something in the database, which sadly, is the part you have not given us any details about, not even which RDBMS it is. It sounds like you have a SQL Server database that was migrated from some other RDBMS. I suspect that...

Deleting a row using entity framework

c#,entity-framework

You need to use .FirstOrDefault and check whether a valid entity has been found: //select row to delete Doctor del = ((Doctor)cbDocIdd.SelectedItem); Doctor deleted = (from d in MainWindow.nlh.Doctors where d.DoctorID == del.DoctorID select d).FirstOrDefault(); // check if it even exists!! if(deleted != null) { //delete row from db MainWindow.nlh.Doctors.DeleteObject(deleted);...

Entity Framework - How to get Standard Deviation using GroupBy?

.net,entity-framework,aggregation,standard-deviation

You should be able to use EntityFunctions.StandardDeviation in System.Data.Objects like this: StdDev = EntityFunctions.StandardDeviation(s.Select(m => m.Minutes)) (If you were using EF 6, it would be System.Data.Entity.DbFunctions.StandardDeviation())...

EF Code first - many to many relation mapping table with extra columns

entity-framework,ef-code-first,entity-framework-6,code-first-migrations

I think it'll work if you do the following: Remove the configuration you showed in the code snippet above Add a mapping table and configure its table name to match the original table name. // name this whatever you want class UserUserGroupMapping { public UserUserGroupMappingId { get; set; } public...

Is querying directly against tables somehow okay now?

sql,entity-framework

Does Entity Framework do something under the hood that makes this practice okay now? EF doesn't really change the dynamic. It is a convenience of data access and rapid development, not a better way to get data. If so, what does it do? It does not. It does, I...

Unable to cast code first

c#,entity-framework,entity-framework-6,code-first

Since User.Operations is supposed to be a collection property (and not a reference property), you need to use HasMany: modelBuilder.Entity<User>() .HasMany(a => a.Operations) .WithOptional() .WillCascadeOnDelete(true); Originally, you were telling EF that User.Operations is a reference property, which causes an error when you try to assign a collection to it....

Entity Framework: how to annotate two one-to-one relationships to same table

entity-framework

You need to indicate which foreign key matches each navigation property. public class Day { public int DayID { get; set; } public int? PunchId_In { get; set; } public int? PunchId_Out { get; set; } [ForeignKey("PunchId_In")] public virtual Punch PunchIn { get; set; } [ForeignKey("PunchId_Out ")] public virtual Punch...

Entity Framework Code First - Optional/required two-way navigation

entity-framework,ef-code-first,foreign-keys,entity-framework-6,foreign-key-relationship

The problem is EF take by convention you want to create an one-to-one relationship, and in case like this you need to specify which entity is the principal. If you want to create an one to one relationship with a different PK in each entity, you can't declare FK properties...

Using SqlQuery in Entity Framework

sql-server,entity-framework

I was oblivious to the situation at first! Something like this should resolve your issue: var Parameter = new List<SqlParameter>(); Parameter.Add(new SqlParameter("@p1", 1)); Parameter.Add(new SqlParameter("@p2", 2)); Parameter.Add(new SqlParameter("@p3", 3)); context.Database.SqlQuery<myEntityType>("exec sp_Stored_Procedure @ParamOne = @p1, @ParamTwo = @p2, @ParamThree = @p3", Parameter.ToArray()).ToList<myEntityType>(); ...

Property Is Required on Update EF6

c#,asp.net,.net,entity-framework,entity-framework-6

Best workaround I know: entity.Property = "placeholder"; var entry = _context.Entry(entity); entry.State = EntryState.Modified; entry.Property(m => m.Property).IsModified = false; _context.SaveChanges(); You mark entity as modified and then exclude not modified properties. As for validation, you need to set valid value for that field just to pass validation....

Using EF6 code-first, reference same property name

c#,entity-framework,properties,mapping

public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public virtual Address ShippingAddress { get; set; } public int ShippingAddressId { get; set; } public virtual Address...

EntityFramework 6 / SqlCe 4 SaveChangesAsync()

c#,wpf,multithreading,entity-framework,sqlce

After some more testing it appears that I shouldn't be using the await keyword in he call to the async method. Executing the call like this: Task.Run(() => PerformContextSubmitAsync()); Doesn't block the original calling thread, but it doesn't seem to actually execute in an asynchronous fashion. It seem to behave...

Symfony2 relationship between two entities

php,mysql,entity-framework,symfony2

It's normal that the creation of a new email is not associated to a skin object. How could it ? The relation is unidirectional, and only works when you create a skin and you give it an email. To create an email and give it a skin, you have to...

Putting serialized Entity Framework objects back in Database

c#,sql-server,entity-framework

Entity framework doesn't work well with deattached entities, and with your code Entity doesn't know that your Patient exist in database, for this reason try to insert patient too. Try adding context2.Patient.Attach(session2.Patient); before adding session to context....

ModelState.isValid - false

c#,asp.net,asp.net-mvc,entity-framework

A <select> only posts back a single value - it cant bind to property List<MusicStyle> musicStyles You need a view model with properties you can bind to public class BandVM { [Display(Name = "Music style")] [Required(ErrorMessage = "Please select a style")] public string SelectedMusicStyle { get; set; } public SelectList...

Enforce ordering of OData items even when $top is used

linq,entity-framework,asp.net-web-api,odata,iqueryable

To override default sort order, you need to set property EnsureStableOrdering of EnableQueryAttribute to false, like describe here: A true value indicates the original query should be modified when necessary to guarantee a stable sort order. A false value indicates the sort order can be considered stable without modifying the...

EF LINQ - Return entities that contain an entire collection

c#,asp.net,entity-framework,linq-to-entities

.Where(n => n.Tags.All(t => tags.Contains(t.DisplayName))) The way this is currently constructed, you're only going to end up with the Nodes where every tag in Node.Tags has a name in the tags whitelist, which includes Nodes with no tags. You might want to use the answer from here on subsets:...

ConnectionString for ObjectContext in MVC raised Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' error

c#,entity-framework,dbcontext,objectcontext

user id=sa;password=Pass121212; ... Integrated Security=True You are using integrated security (uses current Windows login for authentication) so the username and password here are ignored. You should either change this setting or ensure that your application is running as a user that can access the database....

Get a single text value using linq

c#,asp.net-mvc,linq,entity-framework,asp.net-mvc-3

Change your Select to be a Where. Where uses a predicate to filter the data and return the same structure...just a subset. Select on the other hand changes the data structure to be whatever is evaluated in the provided function. In your case you are changing the structure to be...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework

See Return Or Skip Elements in a Sequence. Take(N) will add TOP N to your SQL and only retrieve N records. For example (using my own SQL Server 2014 with EF 6.1): This LINQ: var query = await dbContext.Lookup .Where(w => w.LookupCd == '1') .Take(10) .ToListAsync(); Generates this SQL: SELECT...

How to map between two entities before paging

c#,asp.net-mvc,entity-framework

You just want to make sure you don't pull anymore records out of the database than you need. As you can't use your ProviderViewModel constructor in LINQ to Entities you will have to retrieve the requested page yourself before creating your view model objects: public ActionResult Index(int? page) { List<ProviderViewModel>...

How to get tables from database first approach without .tt and edmx files?

c#,asp.net-mvc,entity-framework,entity-framework-6

In order to get "Code First from database" install the latest Entity Framework Tools for Visual Studio 2012/2013 (version 6.1.3)

The difference between EF6 and EF4.1 in files hierarchy

c#,entity-framework,visual-studio-2012,entity-framework-6,edmx

So lets make it clear step by step: You've got your .edmx file, which was created from designer or generated from existing database. But it's only an xml file, which contains info about the database structure that is used - storage scheme, info about entities - conceptual schema and mappings...

How return ID or all from another class with Entity Framework?

c#,asp.net,entity-framework,class

I think what you want to do on AddStreet looks like this. You save the Street and return the result. public Street AddStreet(string streetName) { Street street = new Street(); street.StreetName = streetName; using (var _db = new DataContext()) { // Dodaj Street u bazu [AD_STREET] _db.DB_Street.Add(street); _db.SaveChanges(); } //...

How do I mock multiple levels of DbSet.Include lambdas?

entity-framework,unit-testing,lambda,moq

So thanks to @Old Fox reminding me that Moq won't work with static members, I found a way to do this using Microsoft Fakes. Shims allows you to shim static methods. I used Moq to set up Mock<DbSet> objects for each of the entities: var carData = new List<Car>{new Car{...

EF: configuring many to many relationship (code first)

entity-framework

For many-to-many, you can't use a foreign key association. There's a reference to this here: One-to-one relation in EFv4 always uses Foreign Key association and many-to-many relation always uses Independent association. and here: Note: In many-to-many (*:*) you cannot add foreign keys to the entities. In a *:* relationship, the...

N to M relationship code first does not create the foreign key on the M-table

entity-framework,entity-framework-6.1

For a many to many relationship, there is no foreign key on either side. The foreign keys are on the join table, which you have mapped to the table SchoolclassCodePupil: modelBuilder.Entity<SchoolclassCode>(). HasMany(c => c.Pupils). WithMany(p => p.SchoolclassCodes). Map(m => { m.MapLeftKey("SchoolclassCodeId"); m.MapRightKey("PupilId"); m.ToTable("SchoolclassCodePupil"); }); Entity Framework uses that junction table...

How to set default length on all fields in entity framework fluent api?

c#,.net,entity-framework,ef-fluent-api

You can use something called Custom Code First Conventions, but only if you're using Entity Framework 6+. As @ranquild mentions, you can use modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256)); to configure the default maximum length for all string properties. You can even filter which properties to apply your configuration to: modelBuilder.Properties<string>() .Where(p =>...

IronPython entity framwork 6 Could not find attribute where

.net,linq,entity-framework,entity-framework-6,ironpython

Found the issues; I had to use import: import clr import System clr.ImportExtensions(System.Linq) ...

Why does .Where() with a Func parameter executes the query?

c#,oracle,linq,entity-framework

There is a very important difference between Enumerable.Where and Queryable.Where: Enumerable.Where takes a Func<T, bool>. Queryable.Where takes an Expression. Your filter variable is not an Expression, it is a Func<T, bool>, therefore, the compiler uses Enumerable.Where. What happens then is that all rows of your FOO table are transferred to...

Asp.Net Identity find users not in role

asp.net,linq,entity-framework,asp.net-identity

In c# you can get all users that are not in a certain role like this: var role = context.Roles.SingleOrDefault(m => m.Name == "role"); var usersNotInRole = context.Users.Where(m => m.Roles.All(r => r.RoleId != role.Id)); ...

Entity framework to CSV float values

c#,entity-framework,csv

Probably in your case the simplest way to do it is to change the current thread culture then restore it. Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); You can also specify a format provider in (prop.GetValue(entityObject, null) ?? "?").ToString() but in this case you probably need to check if prop.GetValue(entityObject, null) is IFormattable...

ED Code First One to Many Relationship Issue - ASP Identity

entity-framework,ef-code-first,one-to-many

you should try : var user = new ApplicationUser() { UserName = "SuperPowerUser", Email = "[email protected]", EmailConfirmed = true, Forename = "Derek", Surname = "Rivers", DateCreated = DateTime.Now.AddYears(-3), OrganisationUnit = ou }; With your syntax (only provinding a FK) you assume that the Organisation exists....

Why does adding a parameterless constructor to my entity model class work here? What are the implications?

c#,entity-framework,generics,constructor

All Entities linked to EntityFramework must have a Default Constructor. When Entity Framework maps from a database query to your Entities use the default constructor to instantiate a new instance of your Entity to fill it with the data retrieved from your database. If you don't have a default constructor...

Iterating over two lists in c#

c#,asp.net-mvc,linq,entity-framework

you're looping more than you need : foreach (Students newStudents in newStudentData) { var student = currentStudentData.FirstOrDefault(s => s.Id == newStudents.Id); if(student == null) { //add } else { //update } } with FirstOrDefault you can find out if it exists and get a reference to it at the same...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

Entity Framework code-first: querying a view with no primary key

sql,oracle,entity-framework,view,ef-code-first

It's not possible in Entity Framework to have Entities without primary key. Try to get a possible unique key from the views, combining columns, ... to create a unique primary key. If is not possible there is a workaround, if is only a queryable view, with out need to do...

Adding column in Entity Framework 6.1 - Many-To-Many - Code First

c#,entity-framework,ef-code-first,many-to-many,code-first

To add a column to the junction table, you need to map it as an entity explicitly and create two one-to-many relationships: public class PersonCourse { [Key, Column(Order = 0),ForeignKey("Person")] public int PersonId { get; set; } [Key, Column(Order = 1),ForeignKey("Course")] public int CourseId { get; set; } public Person...

Changing the Database Schema on a linking table (many-to-many) in EF

c#,entity-framework,ef-fluent-api

ToTable has an overload in which you can specify the schema name: x.ToTable("UsersAddresses", "Users"); ...

How to display WCF HTTP codes in service response

c#,json,entity-framework,wcf,rest

Probably the most simple approach would be to wrap your results into generic response objects [DataContract] public class Response<T> { [DataMember] public T Result { get; set; } [DataMember] public int Status { get; set; } } // then your declaration Response<List<User>> serverResponse = Response<List<User>>(); // on success serverResponse.Result =...

Should i validate if related entity exists before insert?

c#,entity-framework,domain-driven-design

I usually don't do that. Normally, these information comes from the client which was loaded before (it existed). However, there are cases that the CustomerId is missing at the time you update your db. Due to concurrency when many users access the system at the same time. But this case...

Query to entity framework 7 using linq and related entities

c#,mysql,linq,entity-framework

Ok so i managed (of sort :P) to put all in a single query but i still have to call the .ToList() in order for the next data retrievals to work, if someone has a better solution please let me know . var dataInput = db.VisitedCities .GroupBy(c => c.PersonWhoVisitedNationalityId) .Join(db.Countries,...

How to solve error in Configuration.cs in code first migration

c#,asp.net-mvc,entity-framework

The error you are seeing is likely due to you having multiple classes called Movie. I suggest you take a look at your namespaces and using statements to tidy this up. But, if you cannot change them, specify the type explicitly using the full namespace (I'm guessing which namespace to...

Managing per form ObjectContext lifetime

c#,winforms,entity-framework,orm

As strange as it sounds ,you don't have to dispose you DbContext (IF you haven't manually opened the connection yourself) Have a look at this: Do I always have to call Dispose() on my DbContext objects? Nope That said , I suggest that you use one context per method(and dispose...

DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

c#,entity-framework,entity-framework-6

When you do context.Entry(entity).State = EntityState.Modified;, you are not only attaching the entity to the DbContext, you are also marking the whole entity as dirty. This means that when you do context.SaveChanges(), EF will generate an update statement that will update all the fields of the entity. This is not...

How to create edit view with a dropdownlist

c#,asp.net,asp.net-mvc,entity-framework,asp.net-mvc-3

You can using the following code. In action method : // GET: /GlobalAdmin/Propiedades/Create public ActionResult Create() { ViewBag.EntidadList = new SelectList(_db.Entidades.ToList(). Select(x => new { id= x.Id, nomber= x.Nombre }), "Id", "nombre "); // Viewbag return View(); } In view page : <div class="form-group"> @Html.LabelFor(model => model.Entidad, new { @class...

startIndex cannot be larger than length of string

c#,entity-framework,asp.net-mvc-4

You should have code in following way - string newFilenameExtension = Path.GetExtension("Sample".Trim()); string extn = string.Empty; if (!String.IsNullOrWhiteSpace(newFilenameExtension)) { extn = newFilenameExtension.Substring(1); } if(!String.IsNullOrWhiteSpace(extn)) { // Use extn here } ...

Entity Framework throws Invalid object name

c#,sql-server,entity-framework,ado.net,asp.net-web-api2

Add the connection string to your web.config. The class library's app.config is not used at runtime.

How can I specify the range of rows my LINQ query should retrieve

c#,asp.net-mvc,linq,entity-framework

You could use skip and take, something like this: List<Person> people = db.People .Skip(pageSize * pageNumber).Take(pageSize) .OrderByDescending(t => t.Id) .ToList(); ...

Updating a record using a class object with Entity Framework in C#

c#,entity-framework

Yes you can use it, with the following code void updateBranch(Branches branch) { using (var dbContext = new entitiesContext()) { dbContext.Branches.Attach(branch); dbContext.Entry(branch).State = EntityState.Modified; dbContext.SaveChanges(); } } When you attach a Entity to DBContext, Entity Framework is aware that this instance exist in database and will perform an update operation....

How to use OR in join while using Entity Framework

entity-framework,sql-server-2008

var result = (from t1 in dbContext.tblWISTransacs join t2 in dbContext.tblWCBTransacs on 1 equals 1 where (t1.TicketNo == t2.TicketNo || t1.TicketNo == t2.customernumber) select new { t1, t2 }).ToList(); ...

How to create an input (editorfor) for a field not in the model

c#,asp.net-mvc,entity-framework,asp.net-mvc-3,razor

If you have no particular reason for using editor then replace @Html.Editor(valor) with @Html.TextBox("TextBoxName",valor) ...

How can I verify that RemoveRange has been called on a mock DbContext?

c#,entity-framework,unit-testing,moq

You need to call Verify on the correct mock: mockThingSet.Verify(c => c.RemoveRange(It.IsAny<IEnumerable<Thing>>()), Times.Once); ...

Updating entity framework model using Linq

c#,sql,linq,entity-framework

You need to update your SQL server with the following columns: UserActivity_UserID, Orders_UserId. Or in the code remove this two columns(Map again your DB to the edmx file)....

how to update multiple data in entityframework through async web api

entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2

If I understand your question correctly, it boils down to this: How do I start a long running task from an API call but respond before it is finished. Short Answer: You don't in the API. You delegate to a Service. Long Answer: The error you are getting is most...

Sort a LINQ with another LINQ in MVC

sql-server,linq,entity-framework,controller

Try this: var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber).FirstOrDefault(); var query = from r in db.SQLViewFinalTable where r.MaterialNumber == materialnumb select r But I can not get whay are you filtering by 80254842 and selecting the same value? You can do directly: var query...

LINQ search query doesn't work

c#,asp.net,asp.net-mvc,linq,entity-framework

You are using AND (&&) everywhere, so if at least one of these conditions is false, your where condition will be false. Try using OR conditions instead: where (string.IsNullOrEmpty(nameWithInitials) || tb.NameWithInitials.Contains(nameWithInitials)) && (string.IsNullOrEmpty(studentRegNo) || tbSR.StudentRegistrationNo.Contains(studentRegNo)) && (string.IsNullOrEmpty(NIC) || tb.NIC.Contains(NIC)) && (string.IsNullOrEmpty(fullName) || tbi.Name.Contains(fullName)) In this case in any of these...

Passing conditional parameters to Database.SqlQuery

c#,sql,linq,entity-framework

You can edit your query to this SELECT * FROM Product p WHERE p.ProductId = @ProductId AND (@CustomerId IS NULL OR p.CustomerId = @CustomerId) Then you pass DBNull.Value to @CustomerId if it is not used...