i am trying to implement repository pattern in mvc. but I am stuck. I want to return related data. I have two classes , tbl_Account (contains users )and tbl_Country (contains countries).
public class AccountRepository : IAccount
{
public IEnumerable<Account> GetCountry()
{
var Account = this.storeDB.tbl_UserAccount.Include(s => s.tbl_Country).ToList();
return Account; // it gives error here, saying explicit cast required
}
}
Account is a model class i have created on top of tbl_Account for field validations.
how to cast this or i am missing something else... please please help
1.) Variable name must start lower case.
2.) Method name 'GetCountry' but you return Account.
3.) After include you need to Select countries in account and then return countries.
4.) Please share your entities (model classes) in your question if you wanna get cool answers
Related
I'm having difficulties in two areas:
1) When a user successfully logs into their account using phone auth in Firestore, I take them to an "Edit profile" page so they can add their profile information. I get an error saying that I can't add data to a null user class or add data to a class within a class.
I currently have my user class setup something like the following:
class User {
String points;
Name name;
User({this.points, this.name});
}
class Name {
String firstName;
String lastName;
Name({this.firstName, this.lastName})
}
As you can see, I have a class within a class and when I try to add a value, it says I can't. I've tried doing it like
_bloc.user.name.firstName = value
And I've tried like
Name newName = Name();
newName.first = value.
The second one seems to work but it doesn't seem right. I'm hoping you could help me understand how to properly approach adding data for new users when I have a class within a class.
The second issue is understanding how to properly use the Places API. I'm currently learning from the below repo, but it's outdated and there's a couple lines I can't seem to figure out how to change. I also can't seem to find an updated tutorial since the October app crashing update.
https://github.com/alfianlosari/flutter_placez
Thanks in advance for your help!
i'd like to know whether I could ignore play standard validation when I want to. For instance, let's imagine I have a Entity called Car just like
#Entity
public class Car{
#Id
private Long id;
#Required
private String model;
#Required
private String hiddenField; //important but doesn't appear in some cases (some usecases)
}
In order to make it clearer, then
Case 1
#(carForm : Form[Car])
#import helper._
#form(routes.controller.foo.bar) {
#inputText(carForm("model"))
<input type="submit">
}
Case 2
#(carForm : Form[Car])
#import helper._
#form(routes.controller.foo.bar) {
#inputText(carForm("model"))
#inputText(carForm("hiddenField"))
<input type="submit">
}
Then I have a Play.data.Form object, and it has errors cause i haven't filled model or the hiddenField that was given as exmple. But, actually, i have some situations that this hidden doesn't even appear (case 1), i mean, there's no input called that, as the user is not allowed to edit it that time. So, if I have two usecases, where at the first, all inputs are there and they are supposed to be filled, but the other one has no 'hiddenField' input, but, altought, it's still required by my model, and, of course, a form submitted without it has error as well, what should I do?. How was I supposed to deal with it? I have one model, but validation may be different in one case to another, and i wanna it to be server side, not jquery nor pure javascript.
I tried to discardErrors through
(Imagine it was submitted from case 1)
MyForm<Car> myCarForm = Form.form(Car.class).bindFromRequest();
//it has errors, sure it does, hiddenField was required and that field didn't even exist at screen.
myCarForm.discardErrors(); //ok, error hashmap is empty right now
myCarForm.get(); // anyway, no value here.
//myCarForm.data(); //for sure i could retrieve field by field and remount object that way, but that looks hacky and hardworking
Then, any solution? Thank u all
I got it reading Play for Java book.
6.4.2 Partial Validation
A common use case is having multiple validation constraints for the same object
model. Because we’re defining our constraint on the object model, it’s normal to have
multiple forms that refer to the same object model. But these forms might have different
validation constraints. To illustrate this use case, we can imagine a simple wizard in
which the user inputs a new product in two steps:
1 The user enters the product name and submits the form.
2 The user enters the product EAN number and the description.
We could validate the product’s name during step 2, but displaying an error message
for the product name at that point would be weird. Fortunately, Play allows you to perform
partial validation. For each annotated value, we need to indicate at which step it
applies. We can do that with the help of the groups attribute from our annotations.
Let’s change our Product model class to do that:
public Product extends Model {
public interface Step1{}
public interface Step2{}
#Required(groups = Step1.class)
public String name;
#Required(groups = Step2.class)
public String ean;
}
Then, at Controller
// We re//strict the validation to the Step1 "group"
Form<Product> productForm =
form(Product.class, Product.Step1.class).bindFromRequest();
Thanks!
Yes you can achieve the solution to this problem. what's happening in this case is every time you map your request to model car it will always look for JPA validations for every property then it looks for validate() method present inside that model, if that method returns null then it doesn't pass any error and perform the normal execution, but if it returns any thing then it maps it to form errors.
You can return error mapping to specific field or you can just return a string that will be considered as a global error.
In your case solution is :
#Entity
public class Car{
#Id
private Long id;
private String model;
private String hiddenField; //important but doesn't appear in some cases (some usecases)
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<ValidationError>();
.
.
.
#Some logic to validate fields#
#if field invalid#
errors.add(new ValidationError("model", "errorMessage"));
.
.
.
return errors.isEmpty() ? null : errors;
}
Note: Just remove the JPA validation and use your logic in validate function to check according to the situation.
Ignores validations, like this:
myCarForm.discardErrors().get();
and does the validation otherwise, Jquery for example.
I am using a membership provider that specifies required fields in user such as username and password. You can then inherit this user class to create your own user with any other fields you need.
I added an account like so
public Account AdminAccount { get; set; }
when i now get my user using the membershipprovider it does this:
return _context.Set<TUser>().SingleOrDefault(u => u.Username == username);
The class definition for this membership class looks like so
public class FlexMembershipUserStore<TUser>
: IFlexUserStore
where TUser: class, IFlexMembershipUser, new()
So I send in my user class when creating it, and the class knows about Tuser as a IFlexMembershipUser.
However IFlexMembershipUser does not have my AdminAccount property, only my class that inherits from IFlexMembershipUser has that.
And so when I fetch my user even tho he in the database has a field called AdminAccount_Id which is set correctly I only get AdminAccount to be null.
I see the problem of course with the membership only seeing IFlexMembershipUser and my property not existing on that class but other scalar values are read in properly.
Is there anything I can do about it.
In this particular case I can make the account keep track of it's admins as a user list instead. So I can solve this that way but I am still curious if this can be solved otherwise.
The issue here is that EF only loads things you tell it to for performance reasons. You have two options for loading the remote nav properties, Eager loading (my prefered) or lazy loading.
With Eager loading you tell EF at query time you are interested in the specific nav property and it will go ahead and load it for you. To do this:
using System.Data.Entity;
....
_context.Set<TUser>().Include(u=>u.AdminAccount).SingleOrDefault(u => u.Username == username);
I have read so much (dozens of posts) about one thing:
How to unit test business logic code that has Entity Framework code in it.
I have a WCF service with 3 layers :
Service Layer
Business Logic Layer
Data Access Layer
My business logic uses the DbContext for all the database operations.
All my entities are now POCOs (used to be ObjectContext, but I changed that).
I have read Ladislav Mrnka's answer here and here on the reasons why we should not mock \ fake the DbContext.
He said:
"That is the reason why I believe that code dealing with context / Linq-to-entities should be covered with integration tests and work against the real database."
and:
"Sure, your approach works in some cases but unit testing strategy must work in all cases - to make it work you must move EF and IQueryable completely from your tested method."
My question is - how do you achieve this ???
public class TaskManager
{
public void UpdateTaskStatus(
Guid loggedInUserId,
Guid clientId,
Guid taskId,
Guid chosenOptionId,
Boolean isTaskCompleted,
String notes,
Byte[] rowVersion
)
{
using (TransactionScope ts = new TransactionScope())
{
using (CloseDBEntities entities = new CloseDBEntities())
{
User currentUser = entities.Users.SingleOrDefault(us => us.Id == loggedInUserId);
if (currentUser == null)
throw new Exception("Logged user does not exist in the system.");
// Locate the task that is attached to this client
ClientTaskStatus taskStatus = entities.ClientTaskStatuses.SingleOrDefault(p => p.TaskId == taskId && p.Visit.ClientId == clientId);
if (taskStatus == null)
throw new Exception("Could not find this task for the client in the database.");
if (taskStatus.Visit.CustomerRepId.HasValue == false)
throw new Exception("No customer rep is assigned to the client yet.");
TaskOption option = entities.TaskOptions.SingleOrDefault(op => op.Id == optionId);
if (option == null)
throw new Exception("The chosen option was not found in the database.");
if (taskStatus.RowVersion != rowVersion)
throw new Exception("The task was updated by someone else. Please refresh the information and try again.");
taskStatus.ChosenOptionId = optionId;
taskStatus.IsCompleted = isTaskCompleted;
taskStatus.Notes = notes;
// Save changes to database
entities.SaveChanges();
}
// Complete the transaction scope
ts.Complete();
}
}
}
In the code attached there is a demonstration of a function from my business logic.
The function has several 'trips' to the database.
I don't understand how exactly I can strip the EF code from this function out to a separate assembly, so that I am able to unit test this function (by injecting some fake data instead of the EF data), and integrate test the assembly that contains the 'EF functions'.
Can Ladislav or anyone else help out?
[Edit]
Here is another example of code from my business logic, I don't understand how I can 'move the EF and IQueryable code' out from my tested method :
public List<UserDto> GetUsersByFilters(
String ssn,
List<Guid> orderIds,
List<MaritalStatusEnum> maritalStatuses,
String name,
int age
)
{
using (MyProjEntities entities = new MyProjEntities())
{
IQueryable<User> users = entities.Users;
// Filter By SSN (check if the user's ssn matches)
if (String.IsNullOrEmusy(ssn) == false)
users = users.Where(us => us.SSN == ssn);
// Filter By Orders (check fi the user has all the orders in the list)
if (orderIds != null)
users = users.Where(us => UserContainsAllOrders(us, orderIds));
// Filter By Marital Status (check if the user has a marital status that is in the filter list)
if (maritalStatuses != null)
users = users.Where(pt => maritalStatuses.Contains((MaritalStatusEnum)us.MaritalStatus));
// Filter By Name (check if the user's name matches)
if (String.IsNullOrEmusy(name) == false)
users = users.Where(us => us.name == name);
// Filter By Age (check if the user's age matches)
if (age > 0)
users = users.Where(us => us.Age == age);
return users.ToList();
}
}
private Boolean UserContainsAllOrders(User user, List<Guid> orderIds)
{
return orderIds.All(orderId => user.Orders.Any(order => order.Id == orderId));
}
If you want to unit test your TaskManager class, you should employ the Repository dessign pattern and inject repositories such as UserRepository or ClientTaskStatusRepository into this class. Then instead of constructing CloseDBEntities object you will use these repositories and call their methods, for example:
User currentUser = userRepository.GetUser(loggedInUserId);
ClientTaskStatus taskStatus =
clientTaskStatusRepository.GetTaskStatus(taskId, clientId);
If yout wanto to integration test your TaskManager class, the solution is much more simple. You just need to initialize CloseDBEntities object with a connection string pointing to the test database and that's it. One way how to achieve this is injecting the CloseDBEntities object into the TaskManager class.
You will also need to re-create the test database before each integration test run and populate it with some test data. This can be achieved using Database Initializer.
There are several misunderstandings here.
First: The Repository Pattern. It's not just a facade over DbSet for unit testing! The repository is a pattenr strongly related to Aggregate and Aggreate Root concepts of Domain Driven Design. An aggregate is a set of related entities that should stay consistent to each other. I mean a business consistency, not just only a foreign keys validity. For example: a customer who have made 2 orders should get a 5% discount. So we should somehow manage the consistency between the number of order entities related to a customer entity and a discount property of the customer entity. A node responsible for this is an aggregate root. It is also the only node that should be accessible directly from outside of the aggregate. And the repository is an utility to obtain an aggregate root from some (maybe persistent) storage.
A typical use case is to create a UoW/Transaction/DbContext/WhateverYouNameIt, obtain one aggregate root entity from the repository, call some methods on it or access some other entities by traversing from the root, Commit/SaveChanges/Whatever. Look, how far it differs from yur samples.
Second: The Business Logic. I've already showed you one example: a customer who have made 2 orders should get a 5% discount. In contrary: your second code sample is not a business logic. It's just a query. The responsibility of this code is to obtain some data from the storage. In such a case, the storage technology behind it does matter. So I would recomend integration tests here rather than pretending the storage doesn't matter when interacting with the storage is the sole purpose of this function.
I would also encapsulate that in a Query Object that was already suggested. Then - such a query object could be mocked. Not just DbContext behind it. The whole QO.
The first code sample is a bit better because it probably ivolves some business logic, but that's dificult to identify. Wich leads us to the third problem.
Third: Anemic Domain Model. Your domain doesnt' look very object oriented. You have some dumb entities and transaction scripts over them. With 7 parameters! Thats pure procedural programming.
Moreover, in your UpdateTaskStatus use case - what is the aggregate root? Befere you answer that, the most important question first: what exactly do you want to do? Is that... hmm... marking a current task of a user done when he was visited? Than, maybe there should be a method Visit() inside a Customer Entity? And this method should have something like this.CurrentTaskStatus.IsCompleted = true?
That was just a random guess. If I missed, that would clearly show another issue. The domain model should use the ubiquitous language - something common for the programmer and a business. Your code doesn't have that expressive power that a common language gives. I just don't know what is going on there in UpdateTaskStatus with 7 parameters.
If you place proper expressive methods for performing business operations in your entities that will also enforce you to not use DbContext there at all, as you need your entities to stay persistence ignorant. Then the problem with mocking disappears. You can test the pure business logic without persistence concerns.
So the final word: Reconsider your model first. Make your API expressive by using ubiquitous language first.
PS: Please don't treat me as an authority. I may be completely wrong as I'm just starting to learn DDD.
I'm looking for someone to point me in the right direction (link) or provide a code example for implementing a drop down list for a many-to-one relationship using RequestFactory and the Editor framework in GWT. One of the models for my project has a many to one relationship:
#Entity
public class Book {
#ManyToOne
private Author author;
}
When I build the view to add/edit a book, I want to show a drop down list that can be used to choose which author wrote the book. How can this be done with the Editor framework?
For the drop-down list, you need a ValueListBox<AuthorProxy>, and it happens to be an editor of AuthorProxy, so all is well. But you then need to populate the list (setAcceptableValues), so you'll likely have to make a request to your server to load the list of authors.
Beware the setAcceptableValues automatically adds the current value (returned by getValue, and defaults to null) to the list (and setValue automatically adds the value to the list of acceptable values too if needed), so make sure you pass null as an acceptable value, or you call setValue with a value from the list before calling setAcceptableValues.
I know it's an old question but here's my two cents anyway.
I had some trouble with a similar scenario. The problem is that the acceptable values (AuthorProxy instances) were retrieved in a RequestContext different than the one the BookEditor used to edit a BookProxy.
The result is that the current AuthorProxy was always repeated in the ValueListBoxwhen I tried to edit a BookProxy object. After some research I found this post in the GWT Google group, where Thomas explained that
"EntityProxy#equals() actually compares their request-context and stableId()."
So, as I could not change my editing workflow, I chose to change the way the ValueListBox handled its values by setting a custom ProvidesKey that used a different object field in its comparison process.
My final solution is similar to this:
#UiFactory
#Ignore
ValueListBox<AuthorProxy> createValueListBox ()
{
return new ValueListBox<AuthorProxy>(new Renderer<AuthorProxy>()
{
...
}, new ProvidesKey<AuthorProxy>()
{
#Override
public Object getKey (AuthorProxy author)
{
return (author != null && author.getId() != null) ? author.getId() : Long.MIN_VALUE;
}
});
}
This solution seems ok to me. I hope it helps someone else.