Why do I need to spread operator in the getter method? - dart

so right now, I'm learning about provider state management from maximillian on udemy, and he keeps using spread operator as a getter. For example:
List<Order> _orders = [];
List<Order> get orders {
return [..._orders];
}
Why do we need to use the spread operator?
I can use this code and it runs fine.
List<Order> _orders = [];
List<Order> get orders {
return _orders;
}

The difference between the two examples is that in the first example you are creating a new list containing the elements from _orders. This will make it so if somebody are trying to add a new element to the list returned from orders, it will not make any changes to _orders.
In the second example, you are returning a reference to the _orders list. So any modifications to the list returned from orders will happen to the _orders list.

If you use the spread operator you are making a new list, and not returning the current one you have.
The only reason I can't think of is to be defensive about the data in the list and that it could be modified from outside the object.
TLDR:
Here you get a reference to the list and you could potentially modify it.
List<Order> get orders {
return _orders;
}
And here you are defensive about your data and return a new copy each time the getter gets called.
So the user cannot modify the list wihtout using other method of your class.
List<Order> get orders {
return [..._orders];
}

Related

BreezeJS count of expanded entities

This is using BreezeJS and a Breeze controller through to an EF provider. I have a couple of related Entities, lets call them Customer, which has a Navigation Property called Orders which links to a set of Order Entities for that customer.
What I'd like to display on the UI is a summary of Order Counts for a set of customers who match a partial name search. I can do this through returning all the Order objects, but they're quite large objects and I don't really want to return 100's of them when I don't have to. The inlineCount() method seems to always give the count of the top-level entity (Customer) rather than of the sub-Entities, no matter where I place it in the statement.
var predicate = breeze.Predicate.create('displayName', 'contains', partialName);
return this.entityQuery.from('Customers')
.where(predicate)
.orderBy('displayName')
.using(this.manager)
.expand('Orders')
.execute();
The documentation suggests that you can chain the expand in some way, but I have yet to find a syntax which is valid.
Ideally, I'd like to apply a where to the Orders by a property on Order called Status of say 0 (incomplete) and then give me just the count of those matching Orders. ie, return me all the Customer entities, but have a matching order count for each (rather than the whole list of Order objects and filter client-side).
Would appreciate any pointers in the right direction if it's possible to achieve. My current thinking is that I'll have to create a custom method on the server-side controller and do the work there, but before I make assumptions about what OData can support, I thought I'd check here for some confirmation.
So far, this is my best approach (maybe someone can correct me if there's a better way).
On the server, add this method:
public IQueryable<object> CustomerSummaries()
{
return Context.Customers.Select(p => new
{
Customer = p,
ActiveOrderCount = p.Orders.Count(o => o.Status == 1)
});
}
Then on the client end:
var predicate = breeze.Predicate.create('customer.displayName', 'contains', partialName);
return this.entityQuery.from('CustomerSummaries')
.where(predicate)
.using(this.manager)
.execute();

Dapper.NET mapping with Data Annotations

So I have a class with a property like this:
public class Foo
{
[Column("GBBRSH")
public static string Gibberish { get; set;}
....
}
For saving data, I have it configured so that the update/insert statements use a custom function:
public static string GetTableColumnName(PropertyInfo property)
{
var type = typeof(ColumnAttribute);
var prop = property.GetCustomAttributes(type, false);
if (propr.Count() > 0)
return ((ColumnAttribute)prop.First()).Name;
return property.Name;
}
This handles fine, but I noticed that when I go to retrieve the data, it isn't actually pulling data back via the function for this particular column. I noticed that the other data present was pulled, but the column in question was the only field with data that didn't retrieve.
1) Is there a way to perhaps use the GetTableColumnName function for the retrieval part of Dapper?
2) Is there a way to force Dapper.NET to throw an exception if a scenario like this happens? I really don't want to have a false sense of security that everything is working as expected when it actually isn't (I get that I'm using mapping that Dapper.NET doesn't use by default, but I do want to set it up in that manner).
edit:
I'm looking in the SqlMapper source of Dapper and found:
private static IEnumerable<T> QueryInternal<T>(params) // my knowledge of generics is limited, but how does this work without a where T : object?
{
...
while (reader.Read())
{
yield return (T)func(reader);
}
...
}
so I learned about two things after finding this. Read up on Func and read up on yield (never used either before). My guess is that I need to pass reader.Read() to another function (that checks against column headers and inserts into objects appropriately) and yield return that?
You could change your select statement to work with aliases like "SELECT [Column("GBBRSH")] AS Gibberish" and provide a mapping between the attribute name and the poco property name.
That way, Dapper would fill the matching properties, since it only requires your POCO's to match the exact name of the column.

Constrain the number of child entities in Entity Framework

Bottom Line Up Front
Is there a succinct way that I can constrain the number of child entities that can belong to a parent in Entity Framework. I am using 4.3.1 at the moment.
The Problem
I am developing an ASP.NET MVC3 site which accesses data via a data access layer that uses Entity Framework. I have a SearchList entity which has a many to many relationship to a Search entity. A SearchList may have many Searches, and a Search may belong to many SearchLists.
At one point in the workflow of the site, a user needs to select the searches and other items to use in a batch search. We want the page to load the entire search list.
SearchLists can get quite large, and as a test we created one with 21,000 searches. It took a few seconds, and the data returned was about 9.5 MB, which we were expecting, but jQueryUI choked when trying to table-ify that much.
What we would like
So we want to impose a limit on the number of searches any search list can have. I can go through the application and put a bunch of rules in that checks the size of the collection and if the searches that are trying to be added plus the size of the current... yada yada yada.
If however there was a better way (especially one that could easily output an error message that MVC would pick up) I would totally take that instead.
I have googled, and perused a number of EF blogs to no avail. Constrain children and max number of children in collection and similar searches have returned results that are about Linq queries and the Count and Max methods.
Any help would be appreciated.
There is no built-in way so you will have to code such validation yourselves. Some quick ideas:
You can for example use custom collection for the navigation property which will fire exception when you try to add additional search exceeding the threshold. It is simple but it demands you to have all searches loaded, it will have concurrency problems and moreover it can fire during loading search list and searches from database.
You can handle it in overriden SaveChanges. You will at least have to check how many searches are already related to search list but you will still have concurrency problem (what if other request tries to add search to the same list but only one place is remaining - both can succeed the check and insert related search)
You can handle it in database trigger - again it will have concurrency problems
Avoiding concurrency problems completely requires hand written queries with locking hints to ensure that only one request can check number of searches per search list and insert a new search in atomic transaction.
I ended up going with CustomValidationAttribute, and implemented it with a great deal of success. See below for my implementation info:
In the SearchList entity
[NotMapped]
public String ValidationMessage { get; set; }
[CustomValidation(typeof(EntityValidation.EntityValidators), "ValidateSearchCount")]
public virtual List<Search> Searches { get; set; }
public static bool Create(ProjectContext db, SearchList searchList)
{
try
{
db.SearchLists.Add(searchList);
db.SaveChanges();
return true;
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
searchList.ValidationMessage += validationError.ErrorMessage;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
EntityValidators Class
public static ValidationResult ValidateSearchCount(List<Search> Searches)
{
bool isValid;
int count = Searches.Count();
isValid = (count <= 5000 ? true : false);
if (isValid)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("A maximum of 5000 searches may be added to a SearchList.");
}
}
A similar exception block is on the update method. In this way, when SaveChanges gets called it attempts to validate the entity and its child collections, and when the collection count is greater than 5000 the validator will return an error message which gets caught in the exception handler and stored in a local property for my controller to check when things go wrong.

Why create new generic collection instead of using List<T>?

I want to create card game.
I need to create a collection in order to hold cards.
I can use the List<T> type or create my own generic collection type.
For what reasons should I choose the solution of creating my own collection type?
Update:
1) Thanks all for the quick answers.
2) Actually I need that my card list will be very dynamic.
I need to add and remove cards all the time.
If I want to add specialized methods to the collection
why not to create my own collection that inherit from List ?
3) "A generic list type will allow you to skip the casting of objects back to Cards for instance ..."
If I'm going to use List<T> it is also a generic type so I would not have to use casting.
Well for one thing your deck shouldn't allow you to add, remove or edit cards. It should technically be a read-only array, not a List<>.
In addition to that, it might need specialized methods for say, shuffling, marking cards (giving them to players, marking them as played etc), and so forth.
It all depends on how much effort you want to put in this :)
If List offers the users of your api to do too much, then you might want to create your own type. For example, if you want your users to be able to shuffle the cards, but you don't want them to remove the cards. List offer Remove, Indexer list[13] = new Card, Clear () which mutate the list. Also, if you want specific events to fire, you may want to make your own.
A generic list type will allow you to skip the casting of objects back to Cards for instance ...
public class Card
{
public Suits Suit { get; set; }
public string Value { get; set; }
public Card(Suits suit, string value)
{
this.Suit = suit;
this.Value = value;
}
}
public enum Suits { Heart, Spade, Club, Diamond }
// Generic List
List<Card> cards = new List<Card>();
cards.Add(new Card(Suits.Heart, "Queen"));
cards.Add(new Card(Suits.Club, "Ace"));
cards.Add(new Card(Suits.Diamond, "5"));
// List of Objects
ArrayList list = new ArrayList();
list.Add(new Card(Suits.Heart, "Queen"));
list.Add(new Card(Suits.Club, "Ace"));
list.Add(new Card(Suits.Diamond, "5"));
Console.WriteLine(String.Format("{0} {1}", cards[0].Suit, cards[0].Value));
Console.WriteLine(String.Format("{0} {1}", (list[0] as Card).Suit, (list[0] as Card).Value));
Basically it all depends on what you want. Since you know you are going to be storing cards you may as well use a generic collection.

Adding to EntityCollection adds to the end of collection in Entity Framework?

I'm trying to have a View where the user can add items in a collection without having to go to a new View (the scenario is a sort of CV site where the user adds info about work experience, skills, etc, and it would seem absurd to go to a new View to add each little thing).
So I have an edit View that shows a number of text boxes for the already added items, and there's an ajax call to go to a method to fetch the collection fresh if the user adds an item.
Here are the methods in question:
public ActionResult Edit(int id)
{
Consultant consultant = _repository.GetConsultant(id);
var vm = GetViewModel(consultant);
return View(vm);
}
private DetailsViewModel GetViewModel(Consultant consultant)
{
return new DetailsViewModel
{
Programs = consultant.Programs.ToList(),
Consultant = consultant
};
}
public ActionResult NewProgram(int id)
{
//TODO: ordering is rather strange, because the entitycollection adds at the beginning rather than the end...
Consultant consultant = _repository.GetConsultant(id);
consultant.Programs.Add(new Program());
_repository.Save();
var vm = GetViewModel(consultant);
return PartialView("ProgramList", vm);
}
Now to the question: When the NewProgram method is called, it adds a new program to the Consultant object and creates a new ViewModel to send back, but it adds the new program to the start of the EntityCollection, not at the end. But then when you post the entire form, and you open the Edit View again, the list will have placed the new added program at the end. This is very strange. The user will think he/she adds an item at the start of the list, but if they go back to the page again, they will find the new item at the end.
Why does it do this, and is there any way I can make NewProgram() have the new program added at the end directly?
And if anyone is thinking "he should be using a ViewModel" with DTOs instead of working directly with EF objects, well, I've been down that road for quite a while now ( Entity Framework and MVC 3: The relationship could not be changed because one or more of the foreign-key properties is non-nullable ), and so far no one has shown me explicitly how to achieve this and still be able to both add and remove items in the same View. There is either a problem with maintaining the indexes of the collections or the Entity Framework won't let me save... And the code became a nightmare.
This way I at least have understandable code, and the only thing is I need to have this adding done in the "normal" order, i.e. add at the end of the collection...
Any ideas?
BTW:
This works, but it seems very unnecessary to first have to add the new program to the Consultant object, create the ViewModel without the new program, and then add it to the ViewModel separately...
public ActionResult NewProgram(int id)
{
//TODO: ordering is rather strange, because the entitycollection adds at the beginning rather than the end...
Consultant consultant = _repository.GetConsultant(id);
var vm = GetViewModel(consultant);
var program = new Program();
consultant.Programs.Add(program);
_repository.Save();
vm.Programs.Add(program);
return PartialView("ProgramList", vm);
}
According to http://blogs.msdn.com/b/adonet/archive/2009/12/22/poco-proxies-part-1.aspx , your navigation property Programs is overridden to invoke some kind of DoLazyLoad() method. Since the property instance itself isn't necessarly changed, DoLazyLoad() might actually by asynchronous, which could account for the behavior you're noticing.
Since you are evaluating the list anyhow, you could call ToList() before adding the new program. It would require you to only change the line a bit:
consultant.Programs.ToList().Add(new Program());
If this doesn't work, try:
consultant.Programs.ToList();
consultant.Programs.Add(new Program());
This actually doesn't work well with my "asynchronous" theory, but might help you out.

Resources