Entity Framework Code First Deleting By ID Without Fetching (Generic Style) - entity-framework-4.1

Please tell me if this is a decent approach to deleting an Entity without fetching it given I have the ID.
I have a generic store with the following interface (I'll only show Delete):
public interface IStore : IReadOnlyStore
{
void Delete<TEntity>(TEntity entity) where TEntity : class, IEntity, new();
void SaveChanges();
}
And in the concrete Store class of that interface, here's my delete method:
public void Delete<TEntity>(TEntity entity) where TEntity : class, IEntity, new()
{
var obj = Ctx.Entry(entity);
if (obj.State == System.Data.EntityState.Detached)
{
Ctx.Set(typeof(TEntity)).Attach(obj.Entity);
}
Ctx.Set(typeof(TEntity)).Remove(obj.Entity);
}
I have tested both newing up an Entity:
Store.Delete(new Foo() { Id = request.Entity.Id });
as well as fetching an entity and then calling delete.
Through debugging, I have the desired affect on both scenarios.
I just want to make sure this is a good design and that there are no side effects to this approach.
For reference, Ctx is just the DbContext itself.
Thanks.

It's good design and doesn't have side effects :) (IMHO)
Two remarks:
I'm wondering if you could simplify your Delete method by:
public void Delete<TEntity>(TEntity entity)
where TEntity : class, IEntity, new()
{
Ctx.Entry(entity).State = EntityState.Deleted;
}
I would hope that setting the state to Deleted will attach automatically if the entity isn't already attached. But I am not sure if it works. (Let me know whether it works for attached and detached scenarios (if you should test this).)
If you have performance optimization in mind (avoiding to load the entities) don't forget that, if there are multiple entities to delete in the context, SaveChanges will still send one single DELETE statement per entity to the database. Bulk deletes with EF are quite terrible in performance and it's a terrain where going back to a SQL statements (DELETE ... WHERE ... IN ... many IDs....) sometimes makes sense (if performance matters).

Related

JUnit: Add two duplicated fixtures to some method

Hi I want to test duplication by adding same fixture more than twice. It could be the code below:
#Test(expected=DuplicationException.class)
public void saveFailedWithDuplicatedAccount(){
memberServiceImpl.save(member);
memberServiceImpl.save(member);
}
but I don't know how to deal with Mockito coding - like using when(), verify(). Since I am new to mockito, and I have got nothing found in the Google, so is there any example code to check duplicating addition?
You need to save state somewhere.
It may be some kind of internal storage or real database.
And you can extract logic for searching duplicates and mock that.
For example:
Test(expected = DuplicationException.class)
public void saveFailedWithDuplicatedAccount() {
DuplicateService duplicateServiceMock = Mockito.mock(DuplicateService.class);
memberServiceImpl.setDuplicateService(duplicateServiceMock);
memberServiceImpl.save(member);
Mockito.when(duplicateServiceMock.isDuplicate(member)).thenReturn(true);
memberServiceImpl.save(member);
}
public class DuplicateAccountService {
public boolean isDuplicateAccount(String login) {
return false; // Some logic for find duplicates
}
}

Entity Framework Code First Update Does Not Update Foreign Key

I'm using EF 4.1 Code First. I have an entity defined with a property like this:
public class Publication
{
// other stuff
public virtual MailoutTemplate Template { get; set; }
}
I've configured this foreign key using fluent style like so:
modelBuilder.Entity<Publication>()
.HasOptional(p => p.Template)
.WithMany()
.Map(p => p.MapKey("MailoutTemplateID"));
I have an MVC form handler with some code in it that looks like this:
public void Handle(PublicationEditViewModel publicationEditViewModel)
{
Publication publication = Mapper.Map<PublicationEditViewModel, Publication>(publicationEditViewModel);
publication.Template = _mailoutTemplateRepository.Get(publicationEditViewModel.Template.Id);
if (publication.Id == 0)
{
_publicationRepository.Add(publication);
}
else
{
_publicationRepository.Update(publication);
}
_unitOfWork.Commit();
}
In this case, we're updating an existing Publication entity, so we're going through the else path. When the _unitOfWork.Commit() fires, an UPDATE is sent to the database that I can see in SQL Profiler and Intellitrace, but it does NOT include the MailoutTemplateID in the update.
What's the trick to get it to actually update the Template?
Repository Code:
public virtual void Update(TEntity entity)
{
_dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual TEntity Get(int id)
{
return _dbSet.Find(id);
}
UnitOfWork Code:
public void Commit()
{
_dbContext.SaveChanges();
}
depends on your repository code. :) If you were setting publication.Template while Publication was being tracked by the context, I would expect it to work. When you are disconnected and then attach (with the scenario that you have a navigation property but no explicit FK property) I'm guessing the context just doesn't have enough info to work out the details when SaveChanges is called. I'd do some experiments. 1) do an integration test where you query the pub and keep it attached to the context, then add the template, then save. 2) stick a MailOutTemplateId property on the Publicaction class and see if it works. Not suggesting #2 as a solution, just as a way of groking the behavior. I"m tempted to do this experiment, but got some other work I need to do. ;)
I found a way to make it work. The reason why I didn't initially want to have to do a Get() (aside from the extra DB hit) was that then I couldn't do this bit of AutoMapper magic to get the values:
Publication publication = Mapper.Map<PublicationEditViewModel, Publication>(publicationEditViewModel);
However, I found another way to do the same thing that doesn't use a return value, so I updated my method like so and this works:
public void Handle(PublicationEditViewModel publicationEditViewModel)
{
Publication publication = _publicationRepository.Get(publicationEditViewModel.Id);
_mappingEngine.Map(publicationEditViewModel, publication);
// publication = Mapper.Map<PublicationEditViewModel, Publication>(publicationEditViewModel);
publication.Template = _mailoutTemplateRepository.Get(publicationEditViewModel.Template.Id);
if (publication.Id == 0)
{
_publicationRepository.Add(publication);
}
else
{
_publicationRepository.Update(publication);
}
_unitOfWork.Commit();
}
I'm injecting an IMappingEngine now into the class, and have wired it up via StructureMap like so:
For<IMappingEngine>().Use(() => Mapper.Engine);
For more on this, check out Jimmy's AutoMapper and IOC post.

To DRY or not to DRY? On avoiding code duplication and retaining cohesion

I've got a question concerning code duplication and refactoring, hope it's not too general. Say you've got a rather small piece of code (~5 lines) which is a sequence of function invocations that is - not a very low level. This code is repeated in several places, so it would probably be a good idea to extract a method here. However, in this particular example, this new function would suffer from low cohesion (which manifests itself, among others, by having a hard time finding a good name for the function). The reason for that is probably because this repeated code is just a part of a bigger algorithm - and it's difficult to divide it into well named steps.
What would you suggest in such scenario?
Edit:
I wanted to keep the question on a general level, so that more people can potentially find it useful, but obviously it would be best to back it up with some code sample. The example might not be the best one ever (it smells in quite a few ways), but I hope it does its job:
class SocketAction {
private static class AlwaysCreateSessionLoginHandler extends LoginHandler {
#Override
protected void onLoginCorrect(SocketAction socketAction) throws IllegalAccessException, IOException {
Server.checkAllowedDeviceCount(socketAction._sess.getDeviceID());
socketAction.registerSession();
socketAction._sess.runApplication();
}
}
private static class AutoConnectAnyDeviceLoginHandler extends LoginHandler {
#Override
protected void onLoginCorrect(SocketAction socketAction) throws IllegalAccessException, IOException {
if (Server.isUserRegistered(socketAction._sess.getUserLogin())) {
Log.logSysInfo("Session autoconnect - acquiring list of action threads...");
String[] sa = Server.getSessionList(socketAction._sess.getUserID());
Log.logSysInfo("Session autoconnect - list of action threads acquired.");
for (int i = 0; i < sa.length; i += 7) {
socketAction.abandonCommThreads();
Server.attachSocketToSession(sa[i + 1], socketAction._commSendThread.getSock());
return;
}
}
Server.checkAllowedDeviceCount(socketAction._sess.getDeviceID());
socketAction.registerSession();
socketAction._sess.runApplication();
}
}
private static class OnlyNewSessionLoginHandler extends LoginHandler {
#Override
protected void onLoginCorrect(SocketAction socketAction) throws IllegalAccessException, IOException {
socketAction.killOldSessionsForUser();
Server.checkAllowedDeviceCount(socketAction._sess.getDeviceID());
socketAction.registerSession();
socketAction._sess.runApplication();
}
}
}
Question is too general to really say, but as an exercise:
Suppose you abstract it. Think about what the likely reasons are for wanting to change the resulting 5-line function. Would you want likely make changes that apply to all users, or would you end up having to write a new function that's slightly different from the old one, each time some caller has reason to want a change?
If you would want to change it for all users, it's a viable abstraction. Give it a poor name now, you might think of a better one later.
If you're going to end up splitting this function off into lots of similar versions as your code evolves in future, it's probably not a viable abstraction. You could still write the function, but it's more of a code-saving "helper function" than it is part of your formal model of the problem. This isn't very satisfactory: the repetition of this amount of code is a bit worrying, because it suggests there should be a viable abstraction in there somewhere.
Maybe 4 of the 5 lines could be abstracted out, since they're more cohesive, and the fifth line just so happens to be hanging around with them at the moment. Then you could write 2 new functions: one which is this new abstraction, and the other is just a helper that calls the new function and then executes line 5. One of these functions might then have a longer expected useful life than the other...
To me, the litmus test is: if I need to make a change to this sequence of code in one place, (e.g. add a line, change the order), would I need to make the same change in other locations?
If the answer is yes, then it is a logical, "atomic" entity and should be refactored. If the answer is no, then it's a sequence of operations that happen to work in more than one situation - and if refactored, will likely cause you more trouble in the future.
I was thinking about this lately and I understand exactly what you're getting at. It occurs to me that this is an implementation abstraction more than anything, and is thus more palatable if you can avoid changing an interface. For instance, in C++ I might extract the function into the cpp without touching the header. This somewhat lessens the requirement for the function abstraction to be well-formed and meaningful to the class user since it's invisible to them until they really need it (when adding to the implementation).
For me the operative word is "threshold". Another word for this would probably be "smell".
Things are always in a balance. It sounds like (in this case) like the center of balance is in cohesiveness (cool); and as you've only got a small number of duplicates it's not hard to manage.
If you had some major "event" occur and you went to "1000" duplicates then the balance would have shiftyed and so might you're approach.
To me, a few managable duplicates isn't a signal to refactor (yet); but I'd keep an eye on it.
Inheritance is Your friend!
Don't duplicate code. Even if a single line of code is very long or difficult, refactor it to a separate method with a distinctive name. Think of it like someone who will read Your code in a year. If You name this function "blabla", will the next guy know what this function does without reading it's code? If not, You need to change the name. After a week of thinking like that You'll get used to it and Your code will be 12% more readable! ;)
class SocketAction {
private static abstract class CreateSessionLoginHandler extends LoginHandler {
#Override
protected void onLoginCorrect(SocketAction socketAction) throws IllegalAccessException, IOException {
Server.checkAllowedDeviceCount(socketAction._sess.getDeviceID());
socketAction.registerSession();
socketAction._sess.runApplication();
}
}
private static class AlwaysCreateSessionLoginHandler extends CreateSessionLoginHandler;
private static class AutoConnectAnyDeviceLoginHandler extends CreateSessionLoginHandler {
#Override
protected void onLoginCorrect(SocketAction socketAction) throws IllegalAccessException, IOException {
if (Server.isUserRegistered(socketAction._sess.getUserLogin())) {
Log.logSysInfo("Session autoconnect - acquiring list of action threads...");
String[] sa = Server.getSessionList(socketAction._sess.getUserID());
Log.logSysInfo("Session autoconnect - list of action threads acquired.");
for (int i = 0; i < sa.length; i += 7) {
socketAction.abandonCommThreads();
Server.attachSocketToSession(sa[i + 1], socketAction._commSendThread.getSock());
return;
}
}
super.onLoginCorrect(socketAction);
}
}
private static class OnlyNewSessionLoginHandler extends CreateSessionLoginHandler {
#Override
protected void onLoginCorrect(SocketAction socketAction) throws IllegalAccessException, IOException {
socketAction.killOldSessionsForUser();
super.onLoginCorrect(socketAction);
}
}
}

Updating database row from model

I'm haing a few problems updating a row in my database using Linq2Sql.
Inside of my model I have two methods for updating and saving from my controller, which in turn receives an updated model from my view.
My model methods like like:
public void Update(Activity activity)
{
_db.Activities.InsertOnSubmit(activity);
}
public void Save()
{
_db.SubmitChanges();
}
and the code in my Controller likes like:
[HttpPost]
public ActionResult Edit(Activity activity)
{
if (ModelState.IsValid)
{
UpdateModel<Activity>(activity);
_activitiesModel.Update(activity);
_activitiesModel.Save();
}
return View(activity);
}
The problem I'm having is that this code inserts a new entry into the database, even though the model item i'm inserting-on-submit contains a primary key field.
I've also tried re-attaching the model object back to the data source but this throws an error because the item already exists.
Any pointers in the right direction will be greatly appreciated.
UPDATE:
I'm using dependancy injection to instantiate my datacontext object as follows:
IMyDataContext _db;
public ActivitiesModel(IMyDataContext db)
{
_db = db;
}
There should be an insert in case of the InsertOnSubmit method usage, this is an expected behaviour.
We recommend the Attach() method usage in your Update() method implementation. In case you have IsVersion column in the entity then everything is simple, in the other case you will have to pass the original values also to the Attach call. More information is available here in MSDN.
I fixed this issue by re-obtaining and updating my object in the Update method.
Instead of trying to re-attach or get the data context to realise it was the same object that belonged to it before I basically did as follows:
[HttpPost]
public ActionResult Edit(Activity activity)
{
Activity myActivity = activitiesModel.getActivityById(activity.id);
myActivity.name = activity.name;
myActivity.date = activity.date;
_dbContext.SubmitChanges();
return View(activity);
}
This isn't my exact code and to be more precise, I created another partial class to my datacontext and stored my update code in there.

Saving and Retrieving Entities of different types using LINQtoSQL

Disclaimer: Bit of a C# newbie - first Software Dev gig in awhile after being in QA for a couple years.
I realize flavors of this question have been asked before (inheritance in LINQtoSQL and the like), but I'm hoping I ask the question differently.
In my database, I will have a super-type of "Event" and multiple sub-types: Conference, Meeting and Appointment, for example.
Event
Id (PK)
TypeId (FK EventTypes.Id)
Title
Conference
Id (PK, FK Event.Id)
Cost
Topic
Meeting
Id (PK, FK Event.Id)
Location
Organizer
Appointment
Id (PK, FK Event.Id)
Time
Address
I am using Rob Conery's MVC StoreFront application as a reference. He essentially gets data from the database and creates class objects, manually mapping Event.Id to db.Event.Id, etc.
I'd like to do this with my Events data model - I'd like to retrieve all Events, and have a LINQ expression dynamic enough to create various event types based on some criteria (TypeId, for example).
var result = from e in db.Events
select new IEvent
{
// Little help? ;)
};
It would be great to find a way to make it so each Event Type knows how to save itself and retrieve itself - I fear having to write the same code for each type, only varying the fields. Make sense?
I did see a question posed and someone answered with something like:
public bool Save<T>() {}
The problem is, I'm not sure where to put this code. I'm also not sure if I should use an IEvent interface or an Event partial class.
I will now end this monster question with an advanced Thank You to those that can offer help/suggestions.
--
EDIT: Good progress - going from DB to Views all with IEvent :) (This Question Helped A Lot)
public class SqlEventRepository : IEventRepository
public IQueryable<IEvent> getEvents() {
// Get Events without doing a query for each type..possible?
var eventType1 = {query};
var eventType2 = {query};
return {concat of all queries};
}
public bool SaveEvent(IEvent) {
// Can I avoid calling a save function for each type of event?
}
You could have a helper class to put your Save<T>() method in. Something like SaveEvents class.
When you want to save using LINQ I'm not so sure that you can use generics as you don't know what T is and therefore cannot update properties in your queries.
I'd use inheritance and then where you'd pass a sub-class, use the parent class (Event) as your argument. Then you can quite easily cast to your subclasses to access those properties in your LINQ Queries.
EDIT:
Something like this:
public class Event : IEvent (Interface implement common properties to all Event type classes)
{
// your code
}
public class MeetingEvent : IEvent
{
public string MeetingEvent
{
get;
set;
}
// add IEvent implementation...
}
public class EventManager
{
public void MyMethod (IEvent event)
{
MeetingEvent Mevent = (MeetingEvent)event;
Mevent.DoSomework();
// now you can cast all eventclasses to and from IEvent passed as a parameter.
}
}