LINQ Code Generation Property Names - linq-to-sql

I am using LINQ To SQL to handle data access in a project. For a case where I have multiple foreign keys in a table to the same table (for e.g. CustomerUserId, TechnicianUserId) , it generates the property names like ApplicationUser and ApplicationUser1. Is there a way to tweak the code generator to produce easier to read names.
I was pleasently surprised by LINQPad in this regard. It correctly generates property names (for e.g. in this case CustomerUser and TechnicianUser).

If you use the LINQ2SQL designer, you can select the connection between the two classes and modify the property names (expand Child Property and/or Parent Property in your properties window).

Related

SQLAlchemy override reflected columns dynamically

I'm using SA in a script I'll be using to periodically 'copy' a subset of mysql tables from a 'production' replica to dev/test systems. I had written code to simply reflect the source tables and meta.create_all(destination_engine). Due to the nature of FKs, I now know I need to apply use_alter=True to the ForeignKeys on the tables as I create them so that I won't get CircularDependencyErrors or other problems. I need to assume I dont know how many FK's or their names until I go through the metadata.
I'm new to SA and typically Java programmer (as you will tell :D). I tried to change the use_alter attr. iteratively at first:
tablesd = smeta.tables.items()
for tname, t in tablesd:
for c in t.columns:
for fk in c.foreign_keys:
fk.use_alter = True
smeta.create_all(to_engine)
EDIT: It's important to note that create_all() does NOT throw a CircularDependencyError after I set the use_alter property like I do above. If I remove that code, create_all() does not work. It just doesnt seem to be removing the FKs from the create...
This obviously didn't work. I then read Overriding Reflected Columns in the SA docs, sample being:
mytable = Table('mytable', meta,
Column('id', Integer, primary_key=True), # override reflected 'id' to have primary key
Column('mydata', Unicode(50)), # override reflected 'mydata' to be Unicode, autoload=True)
I'd guess reflecting each table individually then adding use_alter=True in the FK definition would work, but I CANNOT assume the names and values or # of FK's/columns. I read a lot about using DeclarativeBase to do something like this, but I'm not really sure how that would work...
How can I take my arbitrary list of tables, reflect them, then Override the use_alter option on their respective foreign keys? Am I thinking about this the wrong way?
The answer ended up being inside the problem (Imagine that...). Although each ForeignKey object has a use_alter value that can be set, Constraints also have a separate property that can be set (I was not able to find this in the API Documentation. After running it through PyDev's Debugger, I noticed the former were being set, but all the keys that had Constraints associated with them were still False. I set them to true thusly:
for fk in table.foreign_keys:
fk.use_alter=True
fk.constraint.use_alter=True
This seemed to produce the SQL I was looking for and tables were created correctly with no CircularDependencyErrors and metadata.sorted_tables seemed to work fine with no errors. I was actually able to refactor my code and do things the RIGHT way!
For anyone looking to do DB-->DB reflecting with complex FKs using SQLAlchemy, this answer and Tyler Lesmann's article are for you.
*UPDATE: * Using this method has passed a peer review and is now being used as production code. Seems to work well!

Forcing LINQ to use a Stored Procedure when accessing a Database

I've done some searches (over the web and SO) but so far have been unable to find something that directly answer this:
Is there anyway to force L2S to use a Stored Procedure when acessing a Database?
This is different from simply using SPROC's with L2S: The thing is, I'm relying on LINQ to lazy load elements by accessing then through the generated "Child Property". If I use a SPROC to retrieve the elements of one table, map then to an entity in LINQ, and then access a child property, I believe that LINQ will retrieve the register from the DB using dynamic sql, which goes against my purpose.
UPDATE:
Sorry if the text above isn't clear. What I really want is something that is like the "Default Methods" for Update, Insert and Delete, however, to Select. I want every access to be done through a SPROC, but I want to use Child Property.
Just so you don't think I'm crazy, the thing is that my DAL is build using child properties and I was accessing the database through L2S using dynamic SQL, but last week the client has told me that all database access must be done through SPROCS.
i don't believe that there is a switch or setting that out of the box and automagically would map to using t sprocs the way you are describing. But there is now reason why you couldn't alter the generated DBML file to do what you want. If I had two related tables, a Catalog table and CatalogItem tables, the Linq2SQL generator will naturally give me a property of CatalogItems on Catalog, code like:
private EntitySet<shelf_myndr_Previews_CatalogItem> _shelf_myndr_Previews_CatalogItems;
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="CatalogItem", Storage="_CatalogItems", ThisKey="Id", OtherKey="CatalogId")]
public EntitySet<CatalogItem> CatalogItems
{
get
{
return this._CatalogItems;
//replace this line with a sproc call that ultimately
//returns the expected type
}
set
{
this._CatalogItems.Assign(value);
//replace this line with a sproc call that ultimately
//does a save operation
}
}
There is nothing stopping you from changing that code to be sproc calls there. It'd be some effort for larger applications and I'd be sure that you be getting the benefit from it that you think you would.
How about loading the child entities using the partial OnLoaded() method in the parent entity? That would allow you to avoid messing with generated code. Of course it would no longer be a lazy load, but it's a simple way to do it.
For example:
public partial class Supplier
{
public List<Product> Products { get; set; }
partial void OnLoaded()
{
// GetProductsBySupplierId is the SP dragged into your dbml designer
Products = dataContext.GetProductsBySupplierId(this.Id).ToList();
}
}
Call your stored procedure this way:
Where GetProductsByCategoryName is the name of your stored procedure.
http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx

LINQ to SQL table naming

I am using VS2010 and C#
When I map/select my database tables with LINQ to SQL I have to option to change the "member" propery, but when i delete the table (because I changed something in the schema for example) and add it again the member value gets "reset". Is it possible to set/override this member programmaticly, so that I dont have to change it by hand everytime
I mean the member option of
'<'Table Name="dbo.table1" Member="table1">
All L2S ORM classes are partial, so you should be able to encapsulate the table in another property by extending the DataContext class e.g.
public partial class MyDataContext
{
public IEnumerable<Entity> Table
{
get { return DatabaseTable; }
}
}
So in the above scenario you would make your DatabaseTable private and expose it through a another property. You may still need to change that particular piece of code manually if you change the name of your table, but it means you are only changing it once and don't have to change it everytime you reference the table somewhere in your code.

How can I filter choices out of a drop down list when using Dynamic Data?

I feel like this should be easy, but I don't see any way to do it.
I'm using ASP.NET Dynamic Data with Linq to SQL. I've got a table with an Association to the Technician table. The Parent Property is TechAssignment, and on the web form I'm using a DynamicField to display it.
This works fine really, it correctly sees it as a ForeignKeyField and uses that template to give me a dropdown with a list of techs from the Technicians table.
The only problem is that it gives me a list of ALL the technicians, when there are quite a few who are inactive. How can I tell Dynamic Data to filter out inactive technicians so they can't be selected?
LINQ to SQL generates partial classes.
Add a new property (copy from the other foreign key property)
Apply the filter in the get (either by LINQ2SQL or filtering the original property)
Bind to that property
Example UnapprovedContacts in Association table
public partial class Association
{
public IList<Contact> UnapprovedContacts
{
get
{
return Contacts.Where(c => !c.IsApproved).ToList();
}
}
}

Renaming LINQ 2 SQL Entity Properties Through Partial Classes

Can I use partial classes to create properties that points to an association property generated by the L2S designer. Also, will I be able to use the new property in queries?
How can I achieve this?
If you just want to give a different name to the association property, just use the Property page for the association and rename the parent and/or child property. That will change the name of the EntityRef/EntitySet in the class.
EDIT: The downside of using a separate property in a partial class is that LINQ won't be able to use it when generating queries -- essentially you'll be forced to always get the entities before you can use the related properties on the object. By renaming you allow LINQ to use the related properties in constructing the query which can result in a more efficient query. For example, if you want to get entities where a related entity has a particular property value, using the attribute decorated entity will allow LINQ to generate the SQL to pull just those matching values from the database. With the naive property implementation (that simply references the underlying relation property, in effect renaming it), you will be forced to first get all entities, then do the filtering in your application.
Yes you can, but you have to apply the same attributes as the linq2sql generated property i.e.
[Association(Name="Test_TestData", Storage="_TestDatas", ThisKey="SomeId", OtherKey="OtherId")]
public System.Data.Linq.EntitySet<TestData> MyTestDatas
{
get
{
return this.TestDatas;
}
}
TestDatas being the original relation.
Update: A sample query I ran:
var context = new DataClasses1DataContext();
var tests =
from d in context.Tests
where d.MyTestDatas.Any(md=>md.MyId == 2)
select new
{
SomeId = d.SomeId,
SomeData = d.SomeData,
Tests = d.MyTestDatas
};
foreach (var test in tests)
{
var data = test.Tests.ToList();
}