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...
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()...
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...
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...
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...
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> { } ...
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....
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...
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))...
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...
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.
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...
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...
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...
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...
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...
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(); ...
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...
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...
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...
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...
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(); ...
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....
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...
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...
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...
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...
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...
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....
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; ...
.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...
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...
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);...
.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())...
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...
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...
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....
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,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...
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>(); ...
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....
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...
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...
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...
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....
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...
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...
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:...
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....
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...
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...
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...
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>...
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)
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...
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(); } //...
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{...
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...
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...
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 =>...
.net,linq,entity-framework,entity-framework-6,ironpython
Found the issues; I had to use import: import clr import System clr.ImportExtensions(System.Linq) ...
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,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)); ...
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...
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....
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...
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...
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...
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...
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...
c#,entity-framework,ef-fluent-api
ToTable has an overload in which you can specify the schema name: x.ToTable("UsersAddresses", "Users"); ...
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 =...
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...
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,...
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...
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...
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...
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...
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 } ...
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.
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(); ...
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....
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(); ...
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) ...
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); ...
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)....
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...
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...
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...
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...