-1

I'm working to create a c# application, and in a portion of the application; I'm looking to bring in a .csv to a data table; and then basically loop through each row and query a database to see if the data exists.

I'm testing a LINQ query; but I can't seem to get it to run and display anything. I have the following code setup to run below:

I have the database added and the connection tests succesfully; I have the classes setup. I've been following some courses on pluralsight to test; and I'm not sure what exactly I am doing wrong or missing.

Also as a note; the table name is actually ERP.PartTran, and not PartTran, but I wasn't succesful in setting that up for the db context; could that be why?

EDIT: Code added; images removed

public class EpiDB : DbContext
        {
            public DbSet<Tran> PartTran { get; set; }
        }

        public class Tran
        {
            public int TranNum { get; set; }
            public string TranReference { get; set; }
            public string PartNum { get; set; }

        }
        private static void QueryPartTran()
        {
            var db = new EpiDB();
            int tranref = 4650374; //lookup number
            var query = from Tran in db.PartTran
                        where Tran.TranNum == tranref
                        orderby Tran.TranNum
                        select Tran;

            foreach (var Tran in query)
            {
                Debug.Print(Tran.PartNum);
            }
        }
Anh Lai
  • 367
  • 2
  • 9
AaronGDL
  • 69
  • 7
  • 1
    "but I can't seem to get it to run and display anything" is not specifically the same as "Query hanging". If the query "hangs" then there is likely a network timeout issue (ie. cannot connect to server) and/or the query does not complete from the server in a reasonable amount of time. Both of these cases should 'eventually' fail with a timeout. If the query "[doesn't] display anything", maybe it really return no records? And "can't seem to get it to run" could refer to a general compilation failure etc: *make sure to present clear and consistent problem descriptions*. – user2864740 Sep 26 '19 at 19:47
  • Will update to remove the images and display code as text! I apologize all. – AaronGDL Sep 26 '19 at 19:49
  • As an update, it does look like a timeout occurs; or the query doesn't run as I receive a message saying it failed. So it isnt that the query is running and returning no results; I just dont think the query is running correctly. – AaronGDL Sep 26 '19 at 20:01
  • Are you using EntityFramework or EF Core? If so, which version? – Jim G. Sep 26 '19 at 20:07
  • Possible Duplicate: https://stackoverflow.com/q/14902245/109941 – Jim G. Sep 26 '19 at 20:07
  • Possible Duplicate: https://stackoverflow.com/q/20184644/109941 – Jim G. Sep 26 '19 at 20:08
  • I'm using EF 6.1.0 – AaronGDL Sep 26 '19 at 20:12

2 Answers2

0

If you have an existing database schema, the first thing to avoid soft exceptions is to disable schema creation/migration in EF. By default when EF connects to a database and goes to resolve the schema, if it comes across a table that it cannot resolve, it will create it. The clue I see that might be happening in this case is when you say the table is called [ERP].PartTran. I suspect you may find that your database has a new empty table called [dbo].Tran. (assuming SQL Server)

To disable schema creation: In your Db Context constructor

public EpiDB()
{
   Database.SetInitializer<EpiDB>(null);
}

This may go a long ways to identifying any bad schema assumptions that EF is making by convention. Jim's answer would be along the lines of where I would believe your problem will lie.

Entities should map relatively closely, if not identically to your table. Renaming an entity or properties to differ from the table to clarify it in code is fine, but you need to be sure that when you do this, you give EF enough information about your schema so that it can resolve the table correctly. If your table is named "PartTran" and your DbSet instance is named "PartTran", why would you want to name the entity "Tran" rather than "PartTran"?

If your application schema is "ERP" then you can avoid needing to specify the schema name on each entity by adding the following to your DbContext.OnModelCreating():

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.HasDefaultSchema("ERP");

    // ...
}

Otherwise, if you are using multiple schemas then you will need to explicitly map the schema to use with a [Table] attribute or ToTable("{tableName}", "{SchemaName}") in EntityTypeConfig / modelBuilder config.

Next, ensure that your entity fields match the appropriate fields in the table. You don't need to map every field if you don't need them, but at a minimum you do need to map the Primary Key. On a guess from the PartTran entity, I'm guessing you're either missing something like a PartTranId column, or the PK is a composite key using the PartNum and TranNum columns. If you have a PartTranId or similar PK, add it to the entity along with a [Key] attribute. If the PK is a composite:

    public class PartTran
    {
        [Key, Column(Order = 1)]
        public int TranNum { get; set; }
        public string TranReference { get; set; }
        [Key, Column(Order = 2)]
        public string PartNum { get; set; }
    }

This should give you a few ideas to check out against your code base... To go further it would help to amend your question to include the related tables and any entities you have tried creating so far. Something like "PartTran" looks like a joining table for a many-to-many relationship between a "Part" table and a "Tran"(saction?) table. If that is the case there are a number of options how you can efficiently wire this up in EF to get the data out the way you want.

Steve Py
  • 26,149
  • 3
  • 25
  • 43
  • This doesn't solve the problem of the query "hanging". – DavidG Sep 27 '19 at 08:35
  • It isn't clear yet what the issue the OP is seeing. EF's schema creation behaviour can be masking problems with mapping. My response is to look to remove some of the suspect issues I can see from the info they have provided and hopefully get to the root exception. A bit hard to do with a 500 character comment, so let's wait to hear what the OP has tried. If this isn't related then I delete it. – Steve Py Sep 27 '19 at 11:22
  • I'm not saying your comments are wrong or not important, but they categorically don't answer the problem being experienced by the OP. If this was the problem, OP would see an immediate exception message. So yes, OP will bump into these issues, but it would have to be a follow-up question if they can't figure it out themselves. – DavidG Sep 27 '19 at 11:26
-1

Try this:

    public class EpiDB : DbContext
    {
        public DbSet<Tran> PartTran { get; set; }
    }

    [Table("PartTran", Schema = "ERP")]
    public class Tran
    {
        public int TranNum { get; set; }
        public string TranReference { get; set; }
        public string PartNum { get; set; }
    }

And maybe even:

    public class EpiDB : DbContext
    {
        public DbSet<Tran> PartTran { get; set; }
    }

    [Table("PartTran", Schema = "ERP")]
    public class Tran
    {
        [Key] // Is this your primary key field?
        public int TranNum { get; set; }
        public string TranReference { get; set; }
        public string PartNum { get; set; }
    }
Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • Not sure who voted you negative; but I tried your solution below and I get a messagebox saying that an error occured accessing the database. – AaronGDL Sep 26 '19 at 20:16
  • To add to this; I'm getting an entity framework error #50 similar to this link: https://stackoverflow.com/questions/41708261/an-exception-of-type-system-data-sqlclient-sqlexception-microsoft-getting-st However I'm not connecting to a localdb; but remote servers and my connection strings work. – AaronGDL Sep 26 '19 at 20:59
  • Probably because this doesn't answer the question. If the problem was the query pointing at the wrong schema, the query wouldn't hang, it would throw an exception instantly. – DavidG Sep 26 '19 at 21:51