I am using Subsonic with a SqlAzure database and it's working great. I would like to improve my application by implementing the suggested best practice mentioned in this blog article.
According to the article, I could do something like:
var sqlAzureRetryPolicy = ... code omitted ...;
return sqlAzureRetryPolicy.ExecuteAction<IEnumerable<Product>>(() =>
{
// Invoke a LINQ query.
return result;
});
However this would mean that I would have to copy and paste this code snippet all over my solution and I think it would be tedious and error prone, other members of my team could forget, etc. I don't think it's the best solution and I'm wondering if there's a better way.
Anybody has suggestions on how to do it?
Have you looked into implementing an extension method? You can "add" a method to existing classes (including IEnumerable and IQueryable in your case) to make it look like the method is part of the class. Extension methods can be useful to centralize this type of code. Here is a simple article showing how to extend the string class: http://www.developer.com/net/csharp/article.php/3592216/Using-the-New-Extension-Methods-Feature-in-C-30.htm
I personally use extension methods (I created a TryOpen and TryExecuteReader) to do just what you are asking for, but against SqlCommand and SqlConnection classes. So my code sample won't help you for LINQ.
Related
I have my data model already defined and implemented. I can very easily write manually the filter to filter out non-authorized results for the user who sent the query (which would be in the style of: "collection.acl.personId": queryPersonId )
My problem is, where and how should I write this "thing" to be as automatic as possible?
I tried to do it with a custom query and a static method, but did not had any luck on both.
Static method con: I don't want to rewrite all my code to use .then(). I want to keep the current chaining.
Custom query: it simply did not worked, even by following the doc.
Ideal the result would be something like
Model.findWithAcl(filters).lean()
Model.findOneWithAcl(filters).lean()
Note that we are using Typescript. The priority would be to have something working, but having the ability to have a working type would be the second priority right after.
Thanks for any help
Casl mongoose gives a very good way of filtering both results (row level) and fields from collections. Note that it also can be used in the front end.
Great package that works very well with auth0 rights.
https://casl.js.org/v5/en/guide/intro
https://casl.js.org/v5/en/package/casl-mongoose
I was under the impression that Force.com eliminated the necessity of object-relational mapping.
I can't create a an object that extends a custom object like this:
class Program extends Program__C() { public Program() { super(); } }
So to "add a method to the Program__c() object" I have been doing this:
class Program {
Program__c program;
public Program() {
program = new Program__c();
}
}
But then this leads to the same ERM problems that I thought Force was supposed to eliminate by virtue of the intercourse between APEX and the DB.
Is there any way to extend custom objects, or at least add methods to custom objects, in APEX? Am I incorrect in that developers don't have to do ORM?
Thank you,
-Matthew Mosien
As far as I know (and I'm pretty certain), there is no way to extend custom objects in the manner you wish.
What you're doing seems to be a reasonable solution to the problem.
You don't have to do ORM in the sense that any objects and fields you have in your DB are already accessible in your code with no extra effort. However, you can't do much (if anything) to affect your schema programmatically in your code. You're kinda stuck with it.
Hope this helps!
I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
i'm some newbie in this matter of .net
i'm trying understand this new paradigm
i began with linq for SQl
but i found this library, kind of framework of T4
more specifically: subsonic T4
i think it could be very usefull
but the support docs outside are very scarce
my first intention is use them in the very simple form: a catalog
lets say... Users
so...
how can i use the model generated with subsonic
( using the iactiverecord)
to implement the record-navigational part.,...???!!!
i mean
i want a simple form
to create, delete or modify records
and that is fairy easy
but
what about to move among records ?
i found how to get the first, the last record..
but how can i advance or go back among them???
how can i order the records..?
it seems everytime imust query the table..
its so?
but how can imove among the records i already got?
all of the exmples found are very simple
dont touch the matter and/ or are repetitive everywhere
so.. please
if anybody can help me
or give more references...
i'd thank you a lot
gmo camilo
SubSonic can return a List of your objects if you call ExecuteTypedList or ToList on a query e.g.
List<Product> products = Products.All().ToList();
Once you've got a List then you can move around it in memory. Have a look at the following references to learn more about collections in .net:
System.Collections.Generic Namespace
IEnumerable<(Of <(T>)>) Interface
List<(Of <(T>)>) Class
I am looking for information on handling search in different ORMs.
Currently I am redeveloping some old application in PHP and one of requirements is: make everything or almost everything searchable, so user just types "punkrock live" and the app finds videos clips, music tracks, reviews, upcoming events or even user comments labeled that way.
In environment where everything is searchable ORM need to support this feature in two ways:
providing some indexing API on "O" side of ORM
providing means for bulk database retrieval on "R" side
Ideal solution would return ready made objects based on searched string.
Do you know any good end-to-end solutions that does the job, not necessarily in PHP?
If you dealt with similar problem it would be nice to listen what your experience is. Something more than Use Lucene or semantic web is the way oneliners, tho ;-)*
I have recently integrated the Compass search engine into a Java EE 5 application. It is based on Lucene Java and supports different ORM frameworks as well as other types of models like XML or no real model at all ;)
In the case of an object model managed by an ORM framework you can annotate your classes with special annotations (e.g. #Searchable), register your classes and let Compass index them on application startup and listen to changes to the model automatically.
When it comes to searching, you have the power of Lucene at hand. Compass then gives you instances of your model objects as search result.
It's not PHP, but you said it didn't have to be PHP necessarily ;) Don't know if this helps, though...
In a Propel 1.3 schema.xml file, you can specify that you'd like all your models to extend a "BaseModel" class that YOU create.
In that BaseModel, you're going to re-define the save() method to be something like this:
public function save(PropelPDO $con = null)
{
if($this->getIsSearchable())
{
// update your search index here. Lucene, Sphinx, or otherwise
}
return parent::save($conn);
}
That takes care of keeping everything indexed. As for searching, I'd suggest creating a Search class with a few methods.
class Search
{
protected $_searchableTypes = array('music','video','blog');
public method findAll($search_term)
{
$results = array();
foreach($this->_searchableTypes as $type)
{
$results[] = $this->findType($type, $search_term);
}
return $results;
}
}