Arraylist objects database records cleanup - c#

I have a table called Vendors for example. I also created a class called Vendor so that I can fill a ListView with Vendor Objects. Let's say that that table contains two columns ( Name and Phone) therefore my class Vendor contains those two string properties. If I have an ArrayList of Vendor objects and I wish to delete does vendors in the database how could I do this without building the query?
I am building a class to fill the listview dynamically based on whatever query I pass to the constructor of that class. The class then creates a SqlDataReader object to loop through the records. depending on how many columns there are they will dynamically be added to the listview. The only problem is that when I want to delete the selected rows for example (selected rows will be a collection of vendor objects if referred to the above example) sometimes I get errors building the query. sometimes some of the columns are null and I do not know in advance which column will be the primary key. Moreover the class vendors gets constructed dynamically based on the result from the query. So everything is great. I know I can create a linqToSqlClass or maybe bind it to a dataset. It will be nice if I do not have to modify this class. Maybe when I am looping through the records there is some way of finding the primary key of that row.

If you're using SQL 2008 you could create a procedure that accepts a Table-Valued parameter.
Another option is to convert your ArrayList to an XML string and pass that to a stored procedure works with SQL 2000 and greater

I pass the primary key table name to the constructor of that class and I made that field a required parameter. That way I can build the query more easy. I knew I can do this at the beginning I am just trying to avoid having to pass extra parameters to the class if somehow I can prevent that. LinqToSQLdata classes in visual studio enable you to do that.

Related

EntityFrameworkCore reading data using reflection - how to create DbSet when type unknown

I am working with a .Net 6 Console application where I need to read data from tables in a custom DbContext using Microsoft.EntityFrameworkCore
I have added the entities to the model in OnModelCreating() and can get them back using a call to
var entity = ctx.Model.GetEntityTypes().FirstOrDefault(e => e.FullName().InfexOf(tableName) >= 0);
Given that, how to I retrieve a list of data, for example entity.ToList() - the type returned for entity is IEntityType?.
As an alternate (and my preferred way if possible), I have created an array of tables using reflection (they all inherit from BaseTable), they are stored as a list.
I would like to create a DbSet<> using DbContext.Set() so that I can use Find(), AsNoTracking() and other such commands (including write operations).
I have the following:-
IQueryable<Object>dbSet = (IQueryable<Object>)ctx
.GetType()
.GetMethod("Set",1,Type.EmptyTypes)
.MakeGenericMethod(t)
.Invoke(ctx, null);
Which allows me to do something like dbSet.ToList(), but I would really like to cast it to a DbSet.
Does anyone know if it is possible to make such a conversion?
(I am reading only a few records from sets of tables and then writing data back to a different database (with the same tables).
Update: *Another way of thinking about this: I am iterating across a collection of tables. I need to pull out the PK and two other columns (for which I have the name of at runtime) - if the value of column 1 contains a specific value, I need to update the value of column 2 *
You can't really do that. However, you can cast the database value to specific types based on discriminators. Take a look at this https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations

Entity Framework database-first - dynamically adding table to model

I have tables with the same structure but with a letter prefix of every table.
For example:
A_Company, B_Company, C_Company
There is combo box from which the user can select A, B or C, and then the code saves data into the appropriate table.
How can I do this using EF database-first?
I solved this problem adding a column for code prefix and triggers on my base table company for insert update and delete.
As the other commenters have said, it would be much better to refactor the database to a single table. If you can't do that then the only other thing that I can think of is to have a class which will select the table for you.
I would create a new class which has the same properties as your company tables, and also has the descriminator property. This would then be used as the data source for your ui.
in this class you would have to code manually to draw the data from the correct actual table (and save to it) based on the value of the discriminator. This is fine if you have only a few tables, but as your number of identical tables grows large, this will become more of a headache.
It might be possible to have the base tables all inherit from a virtual base class which would help a bit - you could then create a dictionary which the base class could use to switch the final data source on the fly.
As a final thought have you considered:
1. Creating the master table as suggested by the other commentators as a single table and then having views for each company.
Creating the master table as suggested and then having code to create the individual tables from that one at some point prior to their use?

Auto generate class properties by binding to database lookup table

I'm not sure if this is feasible or not but is there a way in C# that will allow me to generate static members or enumrator of all the lookup values in a database table?
For example, if I have a table for countries with 2 columns: code, countryname. I want a way to convert all the rows in this table into a class with properity for each row so I can do the following:
string countryCode = Country.Egypt.Code
Where Egypt is a generated property from the database table.
When you say "to convert all the rows", do you actually mean "to convert all the columns"?
I so, and if your ADO.NET provider supports it, you can use LINQ to SQL to auto-generate a class that has properties that match the columns in your table. You can follow this procedure:
Right-click on your project and Add / New Item / LINQ to SQL Classes. By default, this will generate a DataClasses1.dbml file with DataClasses1DataContext class.
Expand the database connection of interest in the Server Explorer, under Data Connections (you may need to add it there first through right-click on Data Connections).
Pick the table of interest and drag'n'drop it onto the surface of DataClasses1.dbml.
Assuming your table name was COUNRTY with fields NAME and CODE, you can then use it from your code like this:
using (var db = new DataClasses1DataContext()) {
COUNRTY egypt = db.COUNRTies.Where(row => row.NAME == "Egypt").SingleOrDefault();
if (egypt == null) {
// "Egypt" is not in the database.
}
else {
var egypt_code = egypt.CODE;
// Use egypt_code...
}
}
If you actually meant "rows", I'm not aware of an automated way to do that (which doesn't mean it doesn't exist!). Writing a small program that goes through all rows, extracts the actual values and generates some C# text should be a fairly simple exercise though.
But even if you do that, how would you handle database changes? Say, a value is deleted from the database yet it still exists in your program because it existed at the time of compilation? Or is added to the database but is missing from your program?
This cannot be done because Country.Egypt has to be available at compile time. I think your options are:
Generate code for Country class from database. Of course, the question then is how will clients use it?
Keep the Properties statically declared and read their Code from database during application start-up
Keep the properties as well as code statically declared and check them against database during application start-up.
Further to #1 above, if the client code does not depend on individual property names then these are not types but data and you could just as well use a Country.AllCountries property for that is initialized at start-up.

update a database that has not a PK column

nice job
is it possible to update a data base which doesn't have primary key column with a datagridview?(in a winform program)
i use sql express 2008,and wanna do this with dataset approach.
Cheers
Without knowing a significant amount about what exactly you are doing and how you are going about your problem the simple answer is. Yes…
The datagridview in the .Net framework allows for binding to Objects exposing public properties and implementing custom select and update methods. Therefore it allows you to implement your own custom update method if required and allows for you to perform the update based on any column in your underlying database.
You still need a unique column or a combination of columns to differenciate the various rows you are about to update. At the end of the day the DataLayer that is used to access the data will just do an ordinary sql update/insert on your data.
Just to have asked you but your data model seems kind of broken. I mean that a primary key or at least a unique column would be preferable in any case.
It's all about where your data is actually coming from, whether it's using datasets with plain-old-sql, some kind of ORM (NHibernate or Entity-Framework or whatever), typed datasets, linq-2-sql ...
Depending on your datasource you might have to introduce a primary key to your database.
The GridView actually doesn't care about that, in the end it's just displaying a list of data, and to the grid there is no such thing as a primary key. This only matters to the data access technique in order to know which row to update.

linq2sql: using ExceuteQuery<dto> when rows returned are not in my dto? Can i use a generic data type?

been using ExecuteQuery with some success, i.e. where AccessRights is my dto and queryString contains "Exec sp_name param1,param2 etc"
var accessRights =
this.db.ExecuteQuery<AccessRights>(queryString, sqlParams.Values.ToArray()).AsQueryable();
Everything works perfect if what returns from the stored procedure can be mapped perfectly to the type (dto) that i pass in the generic ExecuteQuery
Problem is now i have a stored procedure that returns a non standard column name.
Basically my i hav my AccessRights class (dto) which contains, "userId", "accessRightId", "Description"
but the new stored procedure returns UserId, AccessRightId, "TemporaryDescription".
now i can't change it as other things depend on it... if I do
var accessRights =
this.db.ExecuteQuery<AccessRights>(queryString, sqlParams.Values.ToArray()).AsQueryable();
then i don't see "TemporaryDescription", which i suppose is logical as it doesn't exist
What i need to do is map temporaryDescription back to description.
Any body has any idea how to do this?
You could try adding the [Column(...)] attribute; no idea if that'll work.
A few options that leap to mind:
build a class that does map 1:1 (by name), and then translate this data (via Select, or a LINQ query) into your actual intended class
write a wrapper SP that renames the column (not nice; you'd need a temp table, presumably forcing recompile due to DDL/DML interleave)
drag the SP onto the data-context designer and rename the columns manually in the generated types (consdier this as an automated implementation of the first bullet)
move (refactor) the interesting part of the SP into a UDF that you can call from your existing sp, and use the UDF directly from the data-context (drag the UDF onto the designer)

Categories

Resources