Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all 1698 articles
Browse latest View live

How reduce result set to every nth row

$
0
0

Hi, for a certain query I can get up to a couple of millions of rows in form of time series data. These rows need to be display on a screen with a limited amout of pixels so it makes sense toblur them or in other words to only select every nth row of the original set. Using SQL I'd do something like this (source stackoverflow)

SELECT t.id, t.key
FROM
(
    SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum
    FROM datatable
) AS t
WHERE t.rownum % n = 0   
ORDER BY t.key

The problem is, I would like to do this with LINQ but I just can't figure out how. A methodROW_NUMBER is not known and using an index in the where clause gives me an error.

Query.Where((s, i) => i % n == 0);

Edit: more precisely

Query.Select((s, i) => new { index = i, data = s } ).Where(s => s.index % n == 0).Select(s => s.data)

The only solutions that worked for me so far is to temporarily run the SQL (toList) and filter it afterwards. This however slows down my server significantly. 


Left outer join multiple tables on multiple fields in Linq

$
0
0

Hi All,

I got error message when I am trying to left outer join two tables on two fields. The error message is "The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'". There is a red underline under join.

Below is my Linq query:

 var searchResults = (from a in db.courselist
                                   join b in db.Summary on
                                  new { a.subject,a.catalog } equals
                                   new { b.Subject, b.Catalogno } into ab

                                  where  a.degree_id == 1 
                                  orderby a.degree_sequenceNo
                                  from b  in ab.DefaultIfEmpty()
                                  select new
                                  {
                                      Courselist = a,
                                      Summary = b
                                  }
                                ).ToList();


Summary table:
 public partial class Summary
    {
        public Guid id { get; set; }

        [StringLength(50)]
        public string Subject { get; set; }

        [StringLength(50)]
        public string Catalogno { get; set; }

        [StringLength(150)]
        public string CourseTitle { get; set; }

        [StringLength(255)]
        public string URL { get; set; }
    }
Courselist table:
public partial class Courselist
{
...
  [StringLength(50)]
        public string subject { get; set; }

        [StringLength(50)]
        public string catalog { get; set; }

        [StringLength(150)]
        public string coursetitle { get; set; }


        public double? credits { get; set; }
...}

I have referenced Using System.Linq; Any idea where the problem is? Thanks.

Someone gave me the solution. The problem is

new{ suject = a.subject, catalog = a.catalog } equalsnew{ suject = b.subject, catalog = b.Catalogno}into ab

Weird unnecessary virtuals created by "CodeFirst from database"

$
0
0

I imported a new database, that has PhoneNumbers and PhoneNumberTypes.  (this is happening to all my 'types' tables, but let's keep it simple.

Very simple relationship, PhoneNumber.TypeID must exist in PoneNumberTypes.  

The only thing I did out of the ordinary in the SQL database was I set the relationship to cascade deletes and updates.

Anyhow in PhoneNumberTypes.cs model I get 2 virtual self references that make not effing sense.

       public virtual PhoneNumberType PhoneNumberTypes1 { get; set; }

        public virtual PhoneNumberType PhoneNumberType1 { get; set; }

And in my db I get this.

            modelBuilder.Entity<PhoneNumberType>()
                .HasOptional(e => e.PhoneNumberTypes1)
                .WithRequired(e => e.PhoneNumberType1);

with the red squiggly line where I underlined in the code.

My approach has been to delete the extra virtual fields and clean up the errors in my DB object, but why oh why did the import smite me in this way?

Determining if a list of users are in role is very slow

$
0
0

I am trying to determine the number of users in specific roles. My code works, but it takes almost 3 min to finish the loop. Can some offer a suggestion to speed up the process?

Here is my code.

int adminCount = 0;
int technicianCount = 0;
int salesPersonCount = 0;
int inActiveCount = 0;

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
CompanyAccountRepository DArepository = new CompanyAccountRepository();
iCompanyAccountRepository = DArepository;
List<CompanyAccountDto> companyAccounts =iCompanyAccountRepository.GetAspNetUserIdAccounts(Id);
foreach (var account in companyAccounts)
            {

                if (um.IsInRole(account.AspNetUserId, "CompanyAdmin") && account.Active)
                {
                    adminCount++;
                }
                else if (um.IsInRole(account.AspNetUserId, "SalesPerson") && account.Active)
                {
                    salesPersonCount++;
                }
                else if (um.IsInRole(account.AspNetUserId, "Technician") && account.Active)
                {
                    technicianCount++;
                }

                if (!account.Active)
                {
                    inActiveCount++;
                }
            }

I have tried the async methods for IsInRoleAsync, but it too produces a long wait.

Thanks
Brad

Entity Framework: Industry adaptation of DB First vs. Code First

$
0
0

I would like to know what is the industry adaptation rate of DB first vs. Code First approaches of Entity Framework. Any insights please?

Thank you.

Unable to load the specified metadata resource after deploying

$
0
0

I have an ASP.NET MVC5 web site that uses EF6. When I publish (to disk package) and then deploy the web site, I find that the next time I try to debug in VS2017, I get the above error. For some reason I never worked out, cleaning the solution and rebuilding sorts it out.

Today, I published and deployed, and found that the production web site throws the same error. Having spent a long time searching, it seems that the most common cause of this error is a mistake in the connection string. However, I don't think that's the problem in my case, as 1) the Web.config file hasn't changed for quite some time (I can see the last change in source control, and have published and deployed successfully several times since then) and b) if I copy the connection string from the published Web.config file into the one in VS, then I can run it and it loads the data from the remote database.

Not sure it's relevant, but my PC crashed last week (wobbly memory card) and I had to reinstall Windows 10. This is the first time I've published and deployed since then. However, the file structure within the project hasn't changed, so I wouldn't expect this to be an issue.

Anyone any idea how I find out what's gone wrong here?

Thanks

ASP.NET SQL criteria with null...can't get this to work in SQLDATASOURCE.

$
0
0

OK. I haven't had to ask for help in quite some time on here, but I'm stuck. ASP.net with a SQLDATASOURCE and an MS Access Database as the db. 

This works fine: SelectCommand="SELECT * FROM [xipam_192_168_0_x] WHERE COL2 <> Null"

This does not: SelectCommand="SELECT * FROM [xipam_192_168_0_x] WHERE COL2 = Null"

The Gridview I'm binding pulls up nothing. I have tried 20 different variations of matching a null and I get no data returned in any of them.

I have tried this in the sqldatasource, as well: <asp:AccessDataSource ID="SqlDataSource3"CancelSelectOnNullParameter="False" runat="server"

And I have tried 14 different variations of this as a parameter (for example, WHERE COL2 = @COL2): 

<asp:SessionParameterDefaultValue=""Name="COL2"SessionField="COL2"Type="String"DefaultValue="" /> 

My thought is that setting the DefaultValue to a null string and then having CancelSelectOnNull = False should work. I must be missing something.

I have tried all kinds of variations in the select statement as well, such as ....OR IS NULL. Just getting nada back every time.

This is one of the last things I need on this page, so any help would be greatly appreciated.

Thanks

Is it possible to pass model in stored procedure calling from LINQ

$
0
0

Hi,

We all call Stored procedures with parameters defined in SP but if there are lot of parameters in SP then specifying each becomes tedious task, say about 20 parameters to save record.

Is there any way (using extension method or other way) that we pass our model consisting of all those properties required by SP and still SP gets executed and returns the desired result ?

like

using(var DB = new DatabaseEntities)
{
    var result = DB.SaveUser<UserModel>().FirstOrDefault();
}

OR

using(var DB = new DatabaseEntities)
{
    var result = DB.SaveUser(UserModel>).FirstOrDefault();
}

Whatever way is possible, where UserModel has properties like UserId, Name, Email, Password, PhoneNumber etc.




Many thanks
Vinod


Can't get DB-First model to link to itself with parent/child setup

$
0
0

So I'm using this very simple tutorial on jsTree and how to get it to work with MVC (http://www.c-sharpcorner.com/article/c-treeview-to-mvc-razor-view/), It's simple and I got it working.  It creates a simple model that where it has a primary key "ID" and another column "Pid" which is a reference to its own ID field. This way you spit out a list of ID's and Names to create tree nodes and this "Pid" links back to the parent node's ID. It's basically a recursive model that references itself in order to make a tree.  So this guys creates his model as such

  1.   public class Category  
  2.     {  
  3.         //Cat Id  
  4.         public int ID { getset; }  
  5.   
  6.         //Cat Name  
  7.         public string Name { getset; }  
  8.   
  9.         //Cat Description  
  10.         public string Description { getset; }  
  11.   
  12.         //represnts Parent ID and it's nullable  
  13.         public int? Pid { getset; }  
  14.         [ForeignKey("Pid")]  
  15.         public virtual Category Parent { getset; }  
  16.         public virtual ICollection<Category> Childs { getset; }  
  17.     }  
  18. }  ... And sure enough in the home controller when he queries all the parent rows (where Pid is null), I set mybreakpoint on it and I can see it worked. If, while debugging, I pull up his first "Category" entity, I can see that the "Childs" property contains multiple "Childs" entities, one for each record where the Pid of a row matches the ID of that row I'm inspecting.  This allows jsTree to start building the nodes.

My model is database-first and just as simple, but the only difference is that that I created it by going through the Model wizard and using a stored procedure.. You can't have PK and FK's on stored procedure so I had to add an attribute. Here's my model:


public partial class Category_Result
{

[Key]
public string ID { get; set; }
public string ParentID { get; set; }
public string Description2 { get; set; } 
public Nullable<bool> Selected { get; set; } // This doesn't really matter now, but I plan on using it to pre-check nodes in the jsTree later
[ForeignKey("ParentID")]
public virtual Category_Result Parent { get; set; }
public virtual ICollection<Category_Result> Childs { get; set; }

As you can see, the model is almost exactly the same, except I had to add the [Key] attribute so EF knows what field to match the ForeignKey to., and my keys are strings instead of ints. When I run this and in my HomeController where I pull up a list all my parent records (ie where ParentID is null), it gets the correct entities from the DB... however when i have my breakpoint set and drill into these parent entities that I'm about to pass to the view, the Childs property for each one is NULL. EF didn't seem to make the "JOIN' or the "LINK" from the foreign key to the primary key.  

Here is a quick sample of the data returned by my stored procedure

ParentIDIDDescription2Selected
NULL1ABCDEFGAll Categories0
1ABCDEFG1001Category 10
1ABCDEFG1002Category 20
1ABCDEFG1003Category 30
1ABCDEFG1004ACategory 4A0
1ABCDEFG1005ACategory 5A0

}

As you can see, there are plenty of entities that have a parent ID that match up exactly to the ID of the first record. But the connection just isn't getting made.  Is there something diferent I need to do with my model, pareticularly on the last line to let EF know what to do?

Read Only Data Access with Entity Framework

$
0
0

I am developing a MVC dashboard application with SQL Server. I used Entity Framework Database First concept to get my records.

Scenario

There is an application tool to do all CRUD operations. I need to use there database to populate some reports including charts. This tool uses multiple databases including MySQL and SQL. Connecting to this databases takes so much time mostly around 2-3 minutes.

They give read only permission all databases. I decided to create local sql database specifically used for this dashboard application only. This will separate production and also avoid lock issues and connection issues. I created separate services to import data from production to my staging database and process the data from staging to my dashboard database.

I am using only one database and import needed tables in to this database so that i can use one context in my application.

Clarification:

I used database first approach to created model from database and working fine. Now i am little confused that in the following;

I am using only read not other operations (Edit, Update and Delete). So if i directly use ado.net with stored procedures, any performance difference?

I am thinking like EF will store database in the memory and it less performance that ado.net. But will get advantage of linq to sql. 

Please help to decide this. EF is fine or ado.net is better in this case? 

I think we need create view models manually and map from the stored procedures.

How can I get a value from this navigation property?

$
0
0

New to Entity Framework and this is confusing me.  I have 3 classes "Candidate", "Website" and "WebsiteType".  Candidate has a one to many relationship with Website.  WebsiteType is purely a lookup table to store the type of site being accessed.  I can return the collection of websites for a candidate but cannot figure out how to get the Name property stored in WebsiteType.

Here are the 3 classes:

Candidate.cs
public partial class Candidate
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Candidate()
        {
            this.Websites = new HashSet<Website>();
        }
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string MiddleInitial { get; set; }
        public string NickName { get; set; }
        public string PhotoUrl { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public Nullable<int> NumberOfSignatures { get; set; }
        public Nullable<bool> IncludesSupplementalFiling { get; set; }
        public string Bio { get; set; }
        public Nullable<int> NumberOfVotes { get; set; }
        public Nullable<int> Percentage { get; set; }
        public Nullable<int> CategoryId { get; set; }
        public Nullable<int> OfficeId { get; set; }
        public Nullable<int> PoliticalPartyId { get; set; }
        public virtual Category Category { get; set; }
        public virtual Office Office { get; set; }
        public virtual PoliticalParty PoliticalParty { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Website> Websites { get; set; }
    }

Website.cs
public partial class Website
    {
        public int WebsiteId { get; set; }
        public string Url { get; set; }
        public Nullable<int> WebsiteTypeId { get; set; }
        public Nullable<int> CandidateId { get; set; }
        public virtual Candidate Candidate { get; set; }
        public virtual WebsiteType WebsiteType { get; set; }
    }

WebsiteType.cs
 public partial class WebsiteType
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public WebsiteType()
        {
            this.Websites = new HashSet<Website>();
        }
        public int WebsiteTypeId { get; set; }
        public string SiteName { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Website> Websites { get; set; }
    }

Below is the code I am using to access the data and project to my DTO.  Again my goal is to return the "Name" property from WebsiteType along with my Website collection.  Could anyone point me in the right direction?

 public CandidateDetailsDTO GetCandidateDetails(int id)
        {
            db.Configuration.LazyLoadingEnabled = false;
            var candidate = (from w in db.Websites
                             join c in db.Candidates on w.CandidateId equals c.Id
                             join wt in db.WebsiteTypes on w.WebsiteTypeId equals wt.WebsiteTypeId
                             select new CandidateDetailsDTO
                            {
                                Id = c.Id,
                                LastName = c.LastName,
                                FirstName = c.FirstName,
                                Bio = c.Bio,
                                Address = c.Address,
                                CategoryName = c.Category.CategoryName,
                                PoliticalParty = c.PoliticalParty.PartyName,
                                Office = c.Office.OfficeName,
                                Websites = w.Candidate.Websites
                            }).FirstOrDefault(c => c.Id == id);

Predicates, Expressions and Expression Trees

$
0
0

Hi All,

I recently went through to learn repository based design to access data layer. would you someone help me what exactly below keyword contribution and when we use this approach(Performance)

  • Predicates
  • Expressions
  • Expression Trees

  

Thanks,

Unable to create a constant value of type ''. Only primitive types or enumeration types are supported in this context.

$
0
0

In my MVC controller I have two lists created from completely different models. One model contains a master list of users. Another model contains a smaller subset of "assigned users". I'm trying to create a list of users from this master list that isn't in the other list. I've seen a lot of examples out there, but they only seem to work when the two lists are based on the same model.. I tried this::

var unassignedusers = db.vwUsers.Where(item1 => !Users.Any(item2 => item2.UserID == item1.UserID)).ToList();

db.vwUsers is a model based on a view that contains all users (my master list). 

Users is a complex type returned from a stored procedure that lists all assigned users and I create it like this:

var Users = db.spAssignedUsers_List(param1, param2).ToList();

I get this error:

Unable to create a constant value of type 'MyProject.Models.spAssignedUsers_List_Result'. Only primitive types or enumeration types are supported in this context.

I don't know what it's it's talking about with a "constant value" I'm just trying to compare the "UserID" value from one list type to the "UserID" from another list type.

Get the Newest Record in Datatable for Each ID Using LINQ VB.Net

$
0
0

I have the following datatable.

IDNameDate
440C2018-03-14 11:08:15.703
439B2018-03-14 11:05:19.260
438A2018-03-14 11:05:40.573
440C2018-03-07 08:34:00.000
439B2018-03-14 11:38:00.000
438A2018-03-14 11:40:00.000
441D2018-03-12 13:54:41.497
441D2018-03-14 08:36:00.000
442E2018-03-11 07:26:00.000

I'm looking for a LINQ query in VB.Net that will return the most recent record for each ID. There may be duplicate IDs but there may not.

I'm able to get a single record for each ID with the following...

Dim dups = myDataTable.AsEnumerable().GroupBy(Function(i) i.Field(Of String)("ID")).Where(Function(g) g.Count() > 1).Select(Function(g) g.Key)

...but I'm having a heck of a time getting the newest record for each ID. I could really use some guidance.

Thanks

How EF will fetch data for my query

$
0
0

see the code

            var customers = (from s in db.Customers
                            select new CustomerDTO
                            {
                                CustomerID = s.CustomerID,
                                CompanyName = s.CompanyName,
                                ContactName = s.ContactName,
                                ContactTitle = s.ContactTitle,
                                Address = s.Address
                            });
            customer = customer.OrderBy(m => m.CompanyName);

tell me when the above code will execute the EF will fetch data from customer db table ?

is it IEnumerable type EF query ?

share some knowledge. thanks


After ToList() if i add more where clause then what happen

$
0
0


first line
-------------
var ctx = new SchoolDBEntities()
var student = (from s in ctx.Students
where s.departmentid == 10
select s).ToList();

suppose later if i add more condition like

second line
-------------
student = student.Where(s => s.StudentName == "Test");

so tell me what will happen when 2nd line will execute. again a new db trip will occur or filter will occur on whatever data comes for first line or first query ?

for second where clause filter will occur in memory stored data or a fresh db trip will occur ?

When IEnumerable return data

$
0
0

i am starter programmer. so i have a very basic question.

1) When IEnumerable return data

public IEnumerable<Animals> AllSpotted()
{
return from a in Zoo.Animals
where a.coat.HasSpots == true
select a;
}

people saying IEnumerable<> is deferred execution. see the above code and tell me when i will get animal data

var animal = AllSpotted(); this line cause the IEnumerable to return data ?

when i will call AllSpotted() then all data comes from db or only filter data comes from db ? if all data comes from db then performance will be slow.
so how to increase performance that i want only only filter data should come from db because i used this filter where a.coat.HasSpots == true

share relevant knowledge.

how can i get object from iqueryable

$
0
0

var mp = Products.Where(mpn => mpn.ProductName == App).Take(1);

returns

iqueryable<Product>;

How can i get the product returned  , without using a for each loop ?

for example  :  Product p =  ?? ;

Entity FrameWork Pre-Generated View error

$
0
0

I have gone through some threads to resolve the issue, but I didn't find solution and below error  am getting.Please help me to resolve the issue.

The current model no longer matches the model used to pre-generate the mapping views, as indicated by the ViewsForBaseEntitySets1e90a322cfd882c11bd79f0abcbb3e6902f44f685a0e64a9e23e0024f12bd09e.MappingHashValue property. Pre-generated mapping views must be either regenerated using the current model or removed if mapping views generated at runtime should be used instead. See http://go.microsoft.com/fwlink/?LinkId=318050 for more information on Entity Framework mapping views.

Thanks,

Devender

I have a repository that looks like this

$
0
0
public void Update(List<T> entity)
{
 if (entity == null)
                    throw new ArgumentNullException("entity");

                this._context.SaveChanges();
}

now i want to add a concurrency check, and if a record fails the check it doesn't get update but doesn't stop the others being updated, everything I have seen uses try catch but i am not sure how i get arround it.

Any thoughts would be appriciated.

Viewing all 1698 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>