Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've got some routing with parameters set-up in ASP.NET MVC 4 + Razor.
I am passing a parameter of {id} to the controller... and then on the controller I want to check the following:
A. if the id exists in the database, return view
B. if the id was not provided, redirect to Index
I've no idea how to go about doing those - and searching around doesn't really provide any information.
Could someone show me how to do an if / else statement to check if {id} has been provided?
The controller:
public ActionResult View(int id)
{
return View();
}
You can make your method parameter a nullable int so that it will work for the request urls such as
yourDomainName/yourController/view and yourDomainName/yourController/view/25
public ActionResult View(int? id)
{
if(id!=null) // id came in the request
{
int postId= id.Value;
var postViewModel = new PostViewModel { Id=postId};
// Use postId to get your entity/View model from db and then return view
// The below is the code to get data from Db.
// Read further if your data access method is different.
var db = new MyDbContext()
var post=db.Posts.FirstOrDefault(x=>x.Id==postId);
if(post!=null)
{
postViewModel.Title = post.Title;
return View(postViewModel);
}
return View("PostNotFound"); // Make sure you have this view.
}
//If code reaches here, that means no id value came in request.
return RedirectToAction("Index");
}
Assuming MyDbContext is your DbContext class and you are using Entity framework for data access. If your data access method is different ( ADO.NET/NHibernate etc..), You may update that part of code with your data access code.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
As part of a test, I wish to mock a Get() method using Moq such that it returns a popped value from a Stack every time it’s called.
Unfortunately, Moq’s Setup() methods are only run once and thus, each Get() within my test returns the same top value from the stack on every call.
My test kicks off a process in which multiple Get() methods are called. How would I mock this Get() method such that it pops a new value every time of off a orderedGetOutputs stack?
How about this:
public interface ISomeInterface
{
public string SomeValue { get; set; }
}
[Fact]
public void PropertyReturnsDifferentValueOnEachCall()
{
var stack = new Stack<string>();
stack.Push("World");
stack.Push("Hello");
var mock = new Mock<ISomeInterface>();
mock.SetupGet(s => s.SomeValue).Returns(() => stack.Pop());
// Because the method signature of stack.Pop() matches
// the expectation of Returns(), you could also write
// mock.SetupGet(s => s.SomeValue).Returns(stack.Pop);
var instance = mock.Object;
var resultOne = instance.SomeValue;
var resultTwo = instance.SomeValue;
Assert.NotEqual(resultOne, resultTwo);
}
When mocking a normal method you use .Setup(), but when you mock a property getter you have to use .SetupGet(). Regardless of what you mock, the .Returns() overload takes also a matching Func<> that can do whatever needed.
Moq has a specific function called “SetupSequence”. This will allow you to chain setup and return calls. Either that or you can pre populate the stack with information you’ll need for each call.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to servicestack and using servicestack version 4.5.0.
With reference to the ServiceStack 'session' missing?
Where can I find this base.SessionBag property ? with base keyword I am getting
these intellisense
please help me.
what does this line means:
Inside a Service the dynamic untyped Session Bag was renamed to base.SessionBag.
what does this line means:
Inside a Service the dynamic untyped Session Bag was renamed to base.SessionBag.
when I write base. I find following intellisense
base.Session //-- Property Method
base.SaveSession //--- Extension
base.SessionAs<>
base.SessionFactory //-- Property Method
public class EntryService : Service
{
public object Post(Entry request)
{
var date = request.Time.Date;
var trackedData = (TrackedData)Session= date.ToString();
if(trackedData == null)
trackedData = new TrackedData { Goal = 300 };
trackedData.Total += request.Amount;
Session[date.ToString()] = trackedData;
return new EntryResponse { Id = 1};
}
}
i want like this
Session[date.ToString()] = trackedData;
but an error occurs Cannot apply indexing with [] to an expression of type ServiceStack.CacheAccess.ISession
You have to inherit from ServiceStack's Service base class. You can then access the dynamic Session Bag with base.SessionBag.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to complete my assignment, but I don't know how to create a linked list with multiple branches. I have extracted my data, narrowed it down and then stored it in a List.
List<Route> routes = new List<Route>();
Route contains two string variables: city1Name and city2Name.
Route route = new Route("FirstCity", "SecondCity");
This means that there's a route between FirstCity and SecondCity. Each city can have multiple routes to other cities.
Could someone show me how to store the this data in a linked list?
I understand what a linked list is and I think I could fetch the multiple possible route data using foreach afterwards, but I was not able to write an algorithm for that. :(
You can use List<T>.Add to append any item of type T while T can be any .NET compliant data type. In your case T is Route. So, you can append any value that can be implicitly convertible to Route
routes.Add(route);
Further, In .NET List<T> is not a link list. List<T> is implemented using Array internally. Link List implementation in .NET is LinkList<T>
EDIT
Here is a very simple implementation to find path form one city to other.
static bool TryFindPath(List<Route> routes, string from, string to, int maxDepth) {
if (maxDepth <= 0) // To prevent StackOverFlowException
return false;
// Find all the routes with starting point == `from`
var startingPoints = Routes.Where(r => r.From == from).ToArray();
if (startingPoints.Length == 0) // No such route exists
return false;
// See if any of route directly leads to `to`
var matchingRoute = startingPoints.Where(r => r.To == to).FirstOrDefault();
if (matchingRoute != null) {
routes.Add(matchingRoute); // If so, we found that
return true;
}
// We are stepping into next level, decrease maxDepth by one
maxDepth -= 1;
// Otherwise iterate through all starting points and find path from
// that specific city refered by to our destination
foreach (var route in startingPoints) {
// Clone `routes`
var thisRoutes = new List<Route>(routes);
thisRoutes.Add(route);
if (TryFindPath(thisRoutes, route.To, to, maxDepth)) {
// Copy all newly added routes in `thisRoutes` to original `routes`
for (var i = routes.Count; i < thisRoutes.Count; i++) {
routes.Add(thisRoutes[i]);
}
return true;
}
}
return false;
}
I'm supposing following definition of Route class
class Route {
public string From { get; set; }
public string To { get; set; }
public Route(string from, string to) {
From = from;
To = to;
}
}
You can find working demo here
List<Route> routes = new List<Route>();
Route route = new Route("FirstCity", "SecondCity");
routes.Add(route);
foreach (oneRoute in routes)
{
// The other work you're interested in doing
// oneRoute represents each single route one at a time.
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to update EF record, in method I have EF object and another new objct which I want to use to update data from. But I m not sure how to copy data from new object to existing one.
Help please.
Here is my code:
public int PostHomeLead(string _lead)
{
try
{
int result = 0;
Lead lead = new Lead();
lead = new JavaScriptSerializer().Deserialize<Lead>(_lead);
//check if lead exist with same session id, if so update it other wise add new.
Lead existingLead = new Lead();
existingLead = db2.HomeLoanCustRepo.GetByID(lead.Lead_id);
if (existingLead == null)
{
db2.HomeLoanCustRepo.Insert(lead);
db2.Save();
result = 1;
}
else
{
db2.HomeLoanCustRepo.Update(lead);
db2.Save();
result = 1;
}
return result;
}
catch(Exception ex)
{
throw ex;
}
}
Either map the properties manually:
existingLead.Foo = deserializedLead.Foo;
existingLead.Bar = deserializedLead.Bar;
existingLead.Baz = deserializedLead.Baz;
Or use a library that does this, like AutoMapper.
As for your comment, creating a deep copy is what you seem to be after. Note this allows for overposting or mass assignment when you don't verify which properties may be updated. You'll need to Attach() the cloned object when using cloning or mapping, as it will not be the same object as returned by GetByID(), so Entity Framework's change tracker won't recognize it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to update record with LINQ to SQL but in some case value is same as original value then also Enitty framework create Update query unnecessary.
var objForupdate = context.temp.FirstOrDefault();
if(objForupdate != null)
{
objForupdate.Name = "VJ"; // Original Value also "VJ"
}
// Create update query for above.
context.SaveChanges();
Updated
Hey Steven Wood
Here I have scenario where my DB has 20 fields. Sometime some data is same as original data then also Entity framework create update query for that.
It is simple if data row is not in dirty state then no need to update it. But entity frame work create Update query for that also. Just use profile tool to check what kind of query executed on DB server after SaveChanges() method executed.
Solutions
Use following function to check entity object changed or not. If not then it will change it to EntityState.Unchanged from EntityState.Modified.
public static bool ChangeStateIfNotModified(this EntityObject entity, ObjectContext context)
{
if (entity.EntityState == EntityState.Modified)
{
ObjectStateEntry state = ontext.ObjectStateManager.GetObjectStateEntry(entity);
DbDataRecord orig = state.OriginalValues;
CurrentValueRecord curr = state.CurrentValues;
bool changed = false;
for (int i = 0; i < orig.FieldCount; ++i)
{
object origValue = orig.GetValue(i);
object curValue = curr.GetValue(i);
if (!origValue.Equals(curValue) && (!(origValue is byte[]) || !((byte[])origValue).SequenceEqual((byte[])curValue)))
{
changed = true;
break;
}
}
if (!changed)
{
state.ChangeState(EntityState.Unchanged);
}
return !changed;
}
return false;
}
If you're looking to not execute the update if the two values are the same, why not do something like:
if(objForUpdate.Name != orignalValue){
context.SaveChanges();
}
Make sure you dispose your context where appropriate. For instance, if this is in a MVC controller, I'd dispose your context in the controller's Dispose() method.
You should use String.Empty instead of '' and verify that the value is really the same or not while debugging.
EDIT: Are you sure it's exactly the same value?
If I take a look at the generated code for a property, it looks like this:
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String id
{
get
{
return _id;
}
set
{
if (_id != value)
{
OnidChanging(value);
ReportPropertyChanging("id");
_id = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("id");
OnidChanged();
}
}
}
private global::System.String _id;
So the value are being compared. Verify the code generated and set a breakpoint to debug it. If the state is changed, then a query would occur. If it's not entering inside the if condition and the update query still occur, the problem is elsewhere.