Entity framework using Data Repository pattern - DeepLoading - repository-pattern

I have been implementing a new project which I have decided to use the repository pattern and Entity Framework.
I have sucessfuly implemented basic CRUD methods and I have no moved onto my DeepLoads.
From all the examples and documentation I can find to do this I need to call something like this:
public Foo DeepLoadFoo()
{
return (from foobah in Context.Items.Include("bah").Include("foo").Include("foofoo") select foo).Single();
}
This doesnt work for me, maybe I am trying to be too lazy but what I would like to achieve would be something along the lines of this:
public Foo DeepLoadFoo(Foo entity, Type[] childTypes)
{
return (from foobah in Context.Items.Include(childTypes).Single();
}
Is anything like this possible, or am I stuck with include.include.include.include?
Thanks

This blog post mentions that the Entity Framework ObjectContext has all the metadata about entities and their properties. So maybe you can use that metadata to walk the properties of your entity, and their child properties, etc.
In other words, I believe you should be able to use the metadata to automatically compose Include calls on your query.

Related

Generating Random instances of Avro's SpecificClass Records in avro via AvroTools - is there a better way than this?

I'm trying to see if this is already part of Avro Tools or a better way to automatically create random data in Avro or a SpecificRecord (not GenericRecord) on a java generated class.
Here's an example:
I have a record generated by avro - let's call it SomeAvroGeneratedRecord. I was able to create a static method that does something like this:
SomeAvroGeneratedRecord record = SomeHelper.generateRandomData(SomeAvroGeneratedRecord.class);
So I was able to get this working - but I feel like somehow there's a better way to code this. I'm reaching out to see if someone can improve my answer.
I've been working on creating dummy data for my avro classes. I went ahead and looked at AvroTools and found a holy grail: a wonderful class called org.apache.avro.util.RandomData. It works great!
However, it seems to only output GenericData. What I'm looking for is to take a generated java class and just create all the new instances that I'd like. And I'd like to do it on-the-fly without having to write a line of code for every type I create.
The closest I found to this was a post here on StackOverflow:
convert generic to specific record
I also found this random generator by confluent
However, the above code assumes you have the schema already.
This would allow me to take a random data generic record and convert it to a specific record - but this would still require me to have the schema. So I noticed that the schema is in the generated class as a field SCHEMA$ for all the generated classes. So I used some reflection to get that data:
public static <T extends SpecificRecordBase> T specificAvroRecordGenerator(Class<T> avroClassType) {
try {
Field field = avroClassType.getDeclaredField("SCHEMA$");
return specificAvroRecordGenerator((Schema)field.get(null));
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
#SuppressWarnings("unchecked")
public static <T extends SpecificRecordBase> T specificAvroRecordGenerator(Schema schema) {
GenericRecord test =
(GenericRecord)new RandomData(schema, 1)
.iterator().next();
return (T) SpecificData.get().deepCopy(test.getSchema(), test);
}
Now, the code above DOES work. However, it feels sooo wonky. I'm surprised it works to be honest. I was able to test it and they're passing:
#Test
void testGenericAvroGenerator() {
assertInstanceOf(PipelineDocument.class, SampleAvroData.specificAvroRecordGenerator(PipelineDocument.class));
assertInstanceOf(ParsedArticle.class, SampleAvroData.specificAvroRecordGenerator(ParsedArticle.class));
}
#Test
void testGenericAvroGenerator() {
assertInstanceOf(PipelineDocument.class, SampleAvroData.specificAvroRecordGenerator(PipelineDocument.getClassSchema()));
assertInstanceOf(ParsedArticle.class, SampleAvroData.specificAvroRecordGenerator(ParsedArticle.getClassSchema()));
}
So I ask: is there a better way to do this? I'm using JDK 17/19 for now. So I'm willing to use any new classes available. I'm happy with the results, but just want to make sure I'm not coding some monstrous hack.
I tried the above but I'm using a lot of parts of reflection and the Avro generated classes that I'm not particularly used to. I feel like I can tighten it up a bit and make it a little more clear - or if there's another method that already does something similar to this.
Any advice would be appreciated.

best practice dealing with non persistent properties, frequent updates

i am new to realm and did not found a solution which was satisfies me.
i have an application where i can record tours with gps data and so on. (there are multiple different objects which are stored in realm).
i created a realm singleton which should do all my realm suff (update, create, delete) for my objects.
now i ran into the following problem:
i start a tour and record it. first it is created, everything is fine. then i came to the point where i have to update my tour object and only a few properties (basically each new gps point updates it). an additional requirement is, that there can be properties, which are not persistent in realm and are only on the object instance.
so now i have the options to call realm.add(object, update:true) which overrides all properties.
i cannot say object.prop1 = asdf , object.pro2 = 345 because i have no write context at this level of my logic. so i can update within a realm.create(type, updatedict, update:true)
but the big downside of this approach is, that i have to refetch the object again to "know" the changes on my object instance.
so updating some properties of an object results in:
create dictionary with id(primary key) and properties to change
call update on my realm singleton and passing all necessary data.
call a fetch on my realm instance to get the new object again, which leads me to loose existing not persisted property values.
i doubt i'm the first with such a requirement but i could not find a solution:
Summary:
Realm Singleton class handling all Realm actions within a write context
Different Realm Object classes which can have not persistent objects
Need partially update for some properties
dont want to have realm code in my viewcontrollers logic, only in its manager.
It's hard to suggest something without any code examples but personally I think not having the ability to update the individual properties of your models is not a good idea.
I think you have 2 options:
Add a method to your RealmSingleton that allows you to get write context (to execute a block inside a write transaction), like:
func updateTour(updateBlock: (Tour) -> Void) {
realm.write {
updateBlock(currentTour)
}
}
...
RealmSingleton.shared.updateTour { tour in
tour.property = value
}
Add the convenience methods to update the individual properties of your Tour object:
RealmSingleton.shared.setTourProperty(value)

Emberjs New routing and query string or custom route matcher

I'm trying to migrate my app to the new emberjs routing API.
With old router I had some workarounds to provide similar URI for objects saved by ID and for new objects which described by set of params. This were done for ability of exchange links to objects between users without permanently saving it. This is two simplified valid routes from my app:
/objects/12 // fetch object by id (/objects/:object_id)
/objects/<serialized params> // build new object from params (/objects/:params)
Both of this routes are similar to router because they all have dynamic parts and static parts are equal. So I wrote custom RouteMatcher to pickup right route. Lack of query string parsing forced me to do this hack as quick and semilegal solution, also there is ancient ticket about this feature on github.
With the new router matching has been extracted to separate package (route-recognizer) so I cannot do the trick (or it will be full of hacks and injections).
As I can see I have to choose from these options:
Totally rewrite my URIs and separate all intersecting routes
Rewrite URIs but try to implement query string parser for the new Ember.Router
Put all logic into one route and reimplement only serialize/deserialize methods (something dirty)
Second solution seems to be more clean.
What will be the best non complicated decision? Should I try to find another way?
The current router does not support query-string parameters.
We are tracking this bug at https://github.com/emberjs/ember.js/issues/1773. You may want to follow it.
In the meantime, your best bet is probably to use a dynamic segment and manually serialize (with the serialize hook) and deserialize (with the model hook).

Service design: where should I put my validation code?

I'm a little confused about the concept of services.
Let's assume i want to create a new user.
Right now, i'm checking if all fields are non-empty in Model (project.Web solution) and in UserServices too (project.Services solution). But to validate the email address i have to create a new function.
Should i create that class in project.Services, something like GeneralValidation.cs and use it, or should i separate it from the Services and create a new project?
Until now i didn't create two solutions for Repositories and Services. I just had one solution for testing, other for project.Web, and another solution where i had the a domain folder, repository folder, and a few classes for business logic, but after reading a little about design patterns i've decided to split this.
Maybe i haven't understand yet the meaning of Services. For me, a service is a layer that will consume a repository (like user), and the service layer is where i should do the validation. If this is correct, that's why i don't know where to create the function for email validation for example.
If someone could explain me this i would really be appreciated. I've already read blogs articles, and search similar questions in stackoverflow but i can't be sure if i've really understand it.
Thanks
Services and Repositories are 'first class citizens' in Domain Driven Design, so I do not see why you'd want to put them in a separate project ?
For your specific scenario, why don't you create a 'UserService' which has a method 'CreateUser', which looks for instance like this:
public static class UserService
{
public static CreateUser( User u )
{
var userRepository = RepositoryFactory.CreateUserRepository();
userRepository.Save (u);
SendActivationMailForUser(u);
}
private static void SendActivationMailForUser( User user )
{
....
}
}
Some more information about services can be found here

Repository Pattern - POCOs or IQueryable?

I'm new to the Repository Pattern and after doing a lot of reading on the web I have a rough understanding of what is going on, but there seems to be a conflict of ideas.
One is what the IRepository should return.
I would like to deal in ONLY Pocos so I would have an IRepository implementation for every aggregate root, like so:
public class OrangeRepository: IOrangeRepository
{
public Orange GetOrange(IOrangeCriteria criteria);
}
where IOrangeCriteria takes a number of arguments specific to finding an Orange.
The other thing I have is a number of data back-ends - this is why I got into this pattern in the first place. I imagine I will have an implementation for each, e.g
OrangeRepositoryOracle, OrangeRepositorySQL, OrangeRepositoryMock etc
I would like to keep it open so that I could use EF or NHibernate - again if my IOrangeRepository deals in POCOs then I would encapsulate this within the Repository itself, by implementing a OrangeRepositoryNHibernate etc.
Am I on the right lines?
Thanks
EDIT: Thanks for the feedback, I don't have anyone else to bounce these ideas off at the moment so it is appreciated!
Yes, your version is the safest / most compatible one. You can still use it with about any resources, not only data access ones, but with web services, files, whatever.
Note that with the IQueryable version you still get to work based on your POCOs classes, but you are tied to the IQueryable. Also consider that you could be having code that uses the IQueryable and then turns out it you hit a case where one of the repository's ORM doesn't handle it well.
I use the same pattern as you do. I like it a lot. You can get your data from any resources.
But the advantage of using IQuerable is that you do not have to code your own criteria API like the OrangeCriteria.
When NHibernate gets full Linq support then I may switch to the IQueryable.
Then you get
public class OrangeRepository: IOrangeRepository {
public IQueryable<Orange> GetOranges();
}