I am a little new to linq-to-sql. I was just thinking suppose you wanted a subset of fields (in your db table) to actually be a data model in your application, what do you do? What I have thought of so far is to create a view from the actual db table and build linq-able classes using it.
Or is there a better way of doing this?
try these Walkthrough: Creating LINQ to SQL Classes (O/R Designer)
or these implemented in MVC Creating Model Classes with LINQ to SQL
One option is you can create Anonymous Types and use it.
Related
I am designing a reward system for my game. I have a table called VirtualItem (VI) (key, display_name), the data contained could be (gd, gold), (dm,diomond). Then I have a Reward table (id, reward_items,etc)
Currently reward_items are a json array of VIs: [[{key: dm, count:5},{key:gd, count10]].There is a web portal allowing user to CRUD reward_items.
My question is, should I use the current flat structure, or add another layer in between and use reference in reward_items instead? Something like reward_items: set_id(referring VirtualItemSet table).
Apparently, using flat structure(json array) will make the query easy. But I probably also need to put dislay_name inside the JSON as well. In addition, when VI changes, its hard to update reward_items.
Using relationship makes the db schema more complex, and make backend operation on CRUDs operation of reward_items complicated as well.(need to create VirtualItemSet item on the fly etc). It also make query more complicated. But it will support dynamic change of VI.
Whats your opinion on this? Or there is a better database for this type of senario?
Thanks,
Chen
As you notice: If you use flat column you can't make sql join and keep data consistency by database for foreign keys. In my practice this decision always make problems in future. So i think better don't use flat columns.
I'm trying to show data from multiple tables on a jsf page.
The page is bound with the backing bean.
Now, there are many ways to do it.
Method 1: I can get the entire table_row on the entity object generated by hibernate using the entity objects.
Method 2: I can create POJO's (Value beans) which hold the data and write queries myself in HQL.
NOTE : The data is coming from multiple tables.
Some people suggested the first method and some suggested the second.
Now the question is
When i need specific columns of specific tables, why do i retrieve a whole row from the db but on the other hand a thought comes that what are the entities for, then ?
I hope i explained my problem well.
Please guide.
Personally, I would go with the second method.Just have the backing beans call a DAO method to populate a POJO instance created in the bean. If a lot of the data is not needed. This way you can query only the data you needed, but if you ever thought in the future some of the other data will be used you would already have the backend coded to retrieve it in the entity class where with the pojo you would have to change the DAO, POJO, and JSF.
I have a table in the database with the following columns: ID, Name, Txt. We are using Linq To Sql to implement our DAL. In there another collegue added two extra columns so in the code the same table results: ID, Name, Txt, NameTemp, TxtTemp.
These two "fake" tables are used in different parts of the code in LINQ joins and analyzing with SQL Profiler the parsed SQL query takes the "real" columns and everything works properly.
Now I need to make an INSERT using that table, but I get an exception since also the fake columns are used in the statement.
Since I cannot add the two fake columns in the DB(since unuseful there), is there a way in which I could make an insert with Linq omitting these two columns?
I think i know where you're getting at. You should be able to add properties to a partial linq class no problem, only thing is that if you try and use a linq query against these "fake" columns, you'll get an exception when linqtosql tries to reference a column that doesn't exist in the database. I've been through this before - i wanted to be able to select columns that don't exist in the database (but do in the linq2sql dbml class) and have linq2sql translate the columns into what they really are in the database. Only problem is that there's no real easy way to do this - you can add attributes to the "fake" properties so that linq2sql thinks that NameTmp and TxtTmp are in fact Name and Txt in the sql world, only problem is that when it comes to inserting a record, the translated sql specifies the same column twice (which SQL doesn't like and throws an exception).
You can mark the column with IsDbGenerated = true - that'll let you insert records without getting the double column problem, but you can't update a record without linqtosql complaining that you can't update a computed column. I guess you can use a sproc to get around this perhaps?
I logged a bug with Microsoft a while back, which they'll never fix. The info here might help you get what you need -
http://social.msdn.microsoft.com/Forums/eu/linqtosql/thread/5691e0ad-ad67-47ea-ae2c-9432e4e4bd46
https://connect.microsoft.com/VisualStudio/feedback/details/526402/linq2sql-doesnt-like-it-when-you-wrap-column-properties-with-properties-in-an-interface
LINQ is not for inserting data, but for querying only - Language INtegrated Query. Use ADO.NET for inserting the data.
(Leaving the first part to remind my stupidity)
Check ScottGu. The classes generated are partial (mentioned here), so you can put your 2 properties into the editable part and since they won't have any mapping attribute defined, they won't be mapped nor persisted.
I have just started using Linq2sql, it generates all of the Classes after my tables which is awesome. my problem is that i have a lot of objects that have the same name as my tables.
this is forcing my to fully namespace everything which i don’t really like as i think it makes my code look messy.
Has anyone found an elegant way to get around this?
ps: i know about namespace aliases and im not really a fan.
If this really is an issue for you, you can change the name of your generated table items in the Linq designer. Select the table and change the value in the Name field in the properties (L2S keeps track of the source table as a separate item, so the two don't have to be named the same). Note that regenerating your DBML file will wipe these changes out.
Along the lines of Rails convention (which I use in my .net) frequently I will name the database table the plural name and the class the single name eg. Table = Users vs. Class = User.
You could try turning off pluarisation of the names it generates.
Tools -> Options -> Database Tools -> O/R Designer
I am trying to inherit from my generated datacontext in LinqToSQL - something like this
public class myContext : dbDataContext {
public System.Data.Linq.Table<User>() Users {
return (from x in base.Users() where x.DeletedOn.HasValue == false select x);
}
}
But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated.
Hal
Another approach would to be use views..
CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0
As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context.
You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where the discriminator column says which goes to which. Then in your code, just reference the Users.OfType ActiveUsers, which will never include anything deleted.
As a side note, how the heck do you do this with markdown?
Users.OfType<ActiveUsers>
I can get it in code, but not inline
Encapsulate your DataContext so that developers don't use Table in their queries. I have an 'All' property on my repositories that does a similar filtering to what you need. So then queries are like:
from item in All
where ...
select item
and all might be:
public IQueryable<T> All
{
get { return MyDataContext.GetTable<T>.Where(entity => !entity.DeletedOn.HasValue); }
}
You can use a stored procedure that returns all the mapped columns in the table for all the records that are not marked deleted, then map the LINQ to SQL class to the stored procedure's results. I think you just drag-drop the stored proc in Server Explorer on to the class in the LINQ to SQL designer.
What I did in this circumstance is I created a repository class that passes back IQueryable but basically is just
from t in _db.Table
select t;
this is usually referenced by tableRepository.GetAllXXX(); but you could have a tableRepository.GetAllNonDeletedXXX(); that puts in that preliminary where clause to take out the deleted rows. This would allow you to get back the deleted ones, the undeleted ones and all rows using different methods.
Perhaps my comment to Keven sheffield's response may shed some light on what I am trying to accomplish:
I have a similar repository for most
of my data access, but I am trying to
be able to traverse my relationships
and maintain the DeletedOn logic,
without actually calling any
additional methods. The objects are
interrogated (spelling fixed) by a StringTemplate
processor which can't call methods
(just props/fields).
I will ultimately need this DeletedOn filtering for all of the tables in my application. The inherited class solution from Scott Nichols should work (although I will need to derive a class and relationships for around 30 tables - ouch), although I need to figure out how to check for a null value in my Derived Class Discriminator Value property.
I may just end up extended all my classes specifically for the StringTemplate processing, explicitly adding properties for the relationships I need, I would just love to be able to throw StringTemplate a [user] and have it walk through everything.
There are a couple of views we use in associations and they still appear just like any other relationship. We did need to add the associations manually. The only thing I can think to suggest is to take a look at the properties and decorated attributes generated for those classes and associations.
Add a couple tables that have the same relationship and compare those to the view that isn't showing up.
Also, sometimes the refresh on the server explorer connection doesn't seem to work correctly and the entities aren't created correctly initially, unless we remove them from the designer, close the project, then reopen the project and add them again from the server explorer. This is assuming you are using Visual Studio 2008 with the linq to sql .dbml designer.
I found the problem that I had with the relationships/associations not showing in the views. It seems that you have to go through each class in the dbml and set a primary key for views as it is unable to extract that information from the schema. I am in the process of setting the primary keys now and am planning to go the view route to isolate only non-deleted items.
Thanks and I will update more later.