We’re rewarding the question askers & reputations are being recalculated! Read more.
24

EDIT: I apologize from my earlier sample that didn't quite compile. I've fixed it and added a more complete example. You could associate each condition with a strategy for changing the query. Each strategy (called SearchFieldMutator in this example) will hold two things: A way to decide if to apply the strategy. The strategy itself. The first part is a ...


21

If you are likely to grow to 100+ domain objects, I'm making the assumption you will have a lot of logic. I wouldn't access the repositories directly via the controllers, I would add a service layer that is retrieved by the controllers via the UnitOfWork. reason being: Your controller actions are likely to bloat and become unmanageable. As you will have ...


20

You're doing it right - per-request lifestyle is exactly what you need, and you got it; this ensures your favorite IoC container disposes your context at the end of each request, and serves a new instance at each new one. One thing bothers me though, and it's not about your code: Use UnitOfWork and Repository patterns seems to be overkill because whole ...


15

I know this is old, but thought it may be helpful for anyone reading this. If you want to clean up the code, you can always refactor it.. something like this is more readable than the original: public UsersController : Controller { private const int PageSize = 25; public ActionResult Index(int page = 1, string sort = "", UserSearchViewModel search) ...


15

As @Jeff pointed out, this code is ...beautiful. Well done! I like the fluent interface a lot, but the code itself is at first glance... wow. Naming All identifiers follow conventional casing (camelCase for locals and parameters, PascalCase for types and their members). I like that you're using an _underscore prefix for field names, but that's just my ...


15

As you have already mentioned, DbContext is a UoW, and DbSet is a repository -- there is no need to reimplement those patterns, unless you're into ridiculously useless complexity. Entity Framework wraps all pending changes in a transaction for you already, so each DbContext in an application contains DbSets that are somehow related. Blogs and Posts are ...


11

I would agree with @Mike reasoning of avoiding controller bloat via services. Wrapping up DbContext is a leaky abstraction. No matter what, you'll end up in some kind of dependency on EF in your services/controller layer. Besides that, I would avoid an extra layer of UnitOfWork and Repository simply because DbContext wraps that up for you already. Per ...


11

I was just playing around with this concept today. I have a User class defined in another assembly. Then I created three classes "based on" (but not derived from) that User class: CreateUser, EditUser, and DetailsUser. Each contains View-specific DataAnnotations (Required, DataType, etc.). public class CreateUser { [Required] public String FirstName ...


11

I don't believe there is a "right way" or a "wrong way" as such (well maybe there is a wrong way :)). I think it all depends on the context of the situation and what is required. However, I've always been a fan of using ViewModels and DTO's so will suggest that the approach you are doing is a "accepted" way. When I first used this approach I had the same ...


11

You can construct LINQ queries step by step instead of writing them all at once parts = Database.Parts; if (filter == "123") { parts = parts.Where(p => p.Number[0].IsDigit()) } else if (filter != "All") { // Alphabetic filter parts = parts.Where(p => p.Number.StartsWith(filter)) } int totalParts = parts.Count(); parts = parts .OrderBy(p =&...


8

Your code seems really good, I would change the ITestingRepository methods to return IEnumerable<> instead of List<>. Also, I suggest you would add a method signature to your generic repository interface that would let you query your DbContext. public interface IGenericRepository<T> where T : class { T Get(int id); void Create(T ...


7

I wholeheartedly agree that the attributes are evil. But in my opinion having to derive from a base class is just as bad as having to add attributes. Both makes you depend on framework infrastructure you don't need to depend on. (Models should be model logic, and model logic only.) In MVC (3 at least) you can implement a ModelValidatorProvider and a ...


7

Personally I think you are over thinking it. Why not just create a string extension method called FriendlyString or PrepareForUrl and then use the original route @Html.ActionLink(Model.BlogPost.Title, "Index", "Post", new { id = Model.BlogPost.Id, title = Model.BlogPost.Title.FriendlyString() }, null)


7

As this is EF code, assuming you have all the associations set up correctly, you should be able to write it something like this: public IEnumerable<Collection> GetCollectionByUid(long uid) { var result = (from collection in db.UserCollections where collection.uid == uid orderby collection.CreateDate descending select ...


6

Sorting functionality may be implemented in more declarative syntax. First declare associative dictionary as private member of the class. private Dictionary<string, Func<IQueryable<UserListItem>, IQueryable<UserListItem>>> _sortAssoc = new Dictionary<string, Func<IQueryable<UserListItem>, IQueryable<UserListItem>...


6

I'll take a stab at answering your questions and provide some suggestions: If you have FormsAuthentication configured in web.config, it will automatically pull the cookie for you, so you shouldn't have to do any manual population of the FormsIdentity. This is pretty easy to test in any case. You probably want to override both AuthorizeCore and ...


6

In a nutshell there are THREE types of model classes to consider: Data Model classes - These are classes that are used for reading/writing data to/from storage. These classes almost always match your table schemes exactly, plus some navigation properties. If you use entity framework (you should), you will have DBSets of these classes defined on your ...


6

Personally I try to keep the view models as close to DTO's as possible. That way you can have any number of objects populating the data from any number of sources. And, as you mentioned, it helps keep them lean and free of domain logic. If there was only one particular method of doing the transformation I might look at existing mapping solutions i.e. ...


5

I know this is an old question, but I think the problem is timeless. Many to many associations (i.e. without junction class) in Entity Framework are always independent associations, so you can only establish or remove them by manipulating object collections, not primitive key values. Inefficiency is inherent to the implementation. But it is not prohibited ...


5

It feels somewhat awkward to answer a question this old, but there are some things that can be done. First, I want to comment on the naming, simply from the fact that I'm currently building an ASP.NET app which is very large, and I've learned through the process that the ViewModel name becomes cumbersome, and is partially a lie. I've begun to name my 'View ...


5

Don't do the striping on the server. Don't do the striping with JavaScript. Since it's styling, do the striping with CSS.


5

Overall, your code is very good, there is not much to review.. In your ViewModel, you might want to use DataAnnotations to do client (using jquery unobstrusive script)/server validation ex : public class ProductCreateViewModel : ICreateProductCommand { [Required] public string Name { get; set; } [Required] public int Price { get; set; } } ...


5

I cannot believe this went unanswered for 5 and a half years (I guess I can, it is a difficult question to answer) - I'm going to try to answer it from the respect of early 2012, and the respect of today (mid 2017). 2012 The biggest concern I see comes from this line: AsyncManager.Parameters["result"] = WorkflowInvoker.Invoke(wf, arguments)["MvcOutput"] ...


5

There is something wrong with this Method that makes it a bit confusing. protected override bool AuthorizeCore(HttpContextBase httpContext) { if(httpContext.User.Identity.IsAuthenticated) { if(string.IsNullOrEmpty(Roles)) { return true; } else { var rolesOfUser = System.Web.Security.Roles....


5

Just put if, not else if so you can have a cumulative multi criteria search, and one condition in every if. So every condition is easy to read, and if more than one criteria is filled, they will cumulate fine. if (!String.IsNullOrWhiteSpace(searchString)) books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper()); if (!String....


5

Ok, so I just recently arrived at a way of doing this sort of thing that I actually like so let me share. In my opinion, the if statements aren't really the problem, its more that they are not really pertinent to controller code. Actions should strive to contain code only about major decisions of what code path will be executed. Solution: You take ...


5

You should try creating ViewModel classes - they're simple classes which just have a bunch of properties, and you pass them to the view instead of using ViewData or ViewBag. You can make them all inherit off of a base model which has a bunch of show/hide flags (like user1614543 suggested) or put the flags on individual models (the better choice) which get ...


4

I have some suggestions about PremieraTcpClient. The way it is written may lead to unreleased resources. If you have an error then you will remain with a stream and client opened. The correct way to do it is by using try...catch...finally or by using using. Below you can find the code using try catch finally private string Connect() { ...


4

IMHO, member variables should begin with an underscore and be descriptive This is fine private IContentService _content; This is better private IContentService _contentService; BTW, using 'this.' in your constructor is redundant.


Only top voted, non community-wiki answers of a minimum length are eligible