How to persist a model when doing Create / Edit in MVC3 before saving it to the database? - asp.net-mvc-3

basically I am talking about the thing what we had in ASP.NET, called ViewState.
Here is the example, to keep it simple, I have a model Employee:
public class Employee
{
public string EmployeeId { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
My company created records for employees with their EmployeeId, Name and Company.
The employee needs to enter (update) only his Phone number and Address.
When I present a form in Edit / or Create mode for employee to enter this information, EmployeeID, Name and Company outputted just as text, while Phone and Address are editable fields (Html.EditorFor), which allows to keep values entered in the Model object.
When this form is HTTP posted back, lets say, validation fails, and the form is presented to the user again to correct his input (View(model)).
However the values for EmployeeID, Name and Company are lost, since they were not defined as Html.EditorFor, like Phone and Address, and therefore are not preserved, when the submitted model is being passed again into the View.
How do I preserve (persist) in the Model those properties (that are not editable)?
Thank you.

Simply use Html.HiddenFor and store the values on the page. You could also use the mvc futures project and Html.Serialize it, but then you are mimicking viewstate when it's not necessary.

Related

SQLite-net-pcl - Always returning ID as 0 (Xamarin)

I recently moved across from SQLite.NET to SQLite-net-pcl due to the Android 7.0 SQlite issue.
In the process I have updated all my libraries and all is working well with regards to insert/drop etc.
The only issue I have is that every time I retrieve an item from the DB it always has an ID of 0. This is causing problems with updating items. Has anyone had this issue before?
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int ID { get; set; }
public string objectId { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public string Title { get; set; }
Thanks in advance.
Please try using this, this worked for me
using SQLite.Net.Attributes;
[PrimaryKey, AutoIncrement]
public int? Id { get; set; }
Had almost the same situation.
with all rows returning id of 0
class ToDo : Java.Lang.Object
{
[PrimaryKey, AutoIncrement]
public int ID { get; }
except I simply had forgotten to type set; in the property.
one thing that might help someone with this sorta problem is using the
GetMapping() method to get some info on the mapping used when CreateTable() is used to create the table.
as example:
Toast.MakeText(this, db.GetMapping<ToDo>().TableName.ToString(), ToastLength.Long).Show();
Toast.MakeText(this, db.GetMapping<ToDo>().HasAutoIncPK.ToString(), ToastLength.Long).Show();
using this I found out that AutoIncrement (HasAutoIncPK = false) wasn't being set on my table.
See if you created the table with the methods CreateComand(query) and ExecuteNonQuery(). If this is the case, create your table with the CreateTable<Type>() method. The primary key and autoincrement attributes are initialized at the time of creating the table through said method
I have been struggling with the same issue here.
I was manually creating the tables to guarantee a smoother update process moving forwards rather than using the CreateTable methods available.
The fix that I eventually stumbled upon was that I was using the wrong data type for my PRIMARY KEY column.
Wrong definition
[RecordIndexId] int PRIMARY KEY NOT NULL
Correct definition
[RecordIndexId] integer PRIMARY KEY NOT NULL
To add a little context there is a big different between the int and integer data types. Explained in this SO answer
My problem was that I had an internal set for my ID property setter. This had to be public to work correctly.
I'd add this as a comment but alas... I don't have enough rep.

How do I delete a related object with a 1 to 1 relationship in the Entity Framework?

I'm using EF Model First and in my Employee class I have a Manager property with a 1 to 1 relationship to itself, the Employee class:
public partial class Employee
{
public Employee()
{
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Employee Manager { get; set; }
}
Now, when I get an existing object from the database and change the manager with:
employee.Manager = otherEmployeeInstance;
Context.Entry(employee).State = System.Data.EntityState.Modified;
Context.SaveChanges();
It works just fine; however, if I want to remove the manager this will not work:
employee.Manager = null;
It looks to me that I first need to "load" the manager (Employee) instance into the context since this makes it work:
var dummyVar = employee.Manager.Id;
employee.Manager = null;
So the question is, what's the best (proper) way to remove a related object?
obviously, when you want to delete an entity of the one-to-one relationship, the EF doesn't allow to delete it without preparing it before. that is, removing any dependent entity information from that entity. Remember, we are using Relational Database system and any breaking relation without any coordination causes to anomaly and failure.
When you want to remove a relation, you can use this at your controller:
employee.Remove(Manager);//Automatically Removes Navigational Properties at both entities
db.SaveChanges();
Instead of this :
employee.Manager = null;

Modelling objects with changing attribute

I am trying to create a simple program in Ruby to track the price movements of stocks, but I'm not entirely sure of how it should be designed.
Basically, I'm thinking of a class Stock, with all the attributes such as name, desc, etc. However, I'm not sure of how the price attribute would work. Because for each stock, I also want to track the history of prices and plot them on a graph. So, my question is, should I create another class, Prices and associate it with Stock? or is there a better way?
I'm a newbie at OOD and would love some explanation, helpful links or other advice. Thank you in advance.
Some of this will depend on your choice of DB: OO, document, or relational. If you're using the typical relational DB, then you would have a table for prices that represents the one-to-many relationship between prices and stock.
It seems like you should have a separate class for price, because I'm assuming you'll want to track price with time. I know this isn't Ruby, but your Stock class could look something like this:
public class Stock
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Price> PriceHistory { get; set; }
}
And then Price:
public class Price
{
public int StockId { get; set; }
public DateTime PriceDate { get; set; }
public decimal Price { get; set; }
}
Note: You'll need to ignore the fact that the IDs are public, and therefore able to be changed by outside classes. However, this code is presented this way for simplicity.
Hope that helps.

Class diagrams to show relation between classes?

Are class diagrams in visual studio supposed to show relation between classes, for eg. 1 : many.
public class User
{
public string UserId { get; set; }
public List<Role> Roles { get; set; }
}
public class Role {
public int RoleId {get; set;}
public User User {get; set;}
public string UserId {get; set; }
}
Edit:
To clarify.. Class diagram generally isn't supposed to show relations (1:n, m:n etc.) because those relations are for database tables (entities). Classic class diagram is more suited for analysis and design, so it shows associations instead of relations.
Original answer:
Yes you can show 'relations', but you wont see any numbers afaik. It has its own way of showing. Numbers are shown in Entity Framework model for example.
How to show associations:
Move classes into diagram, and then right click on property Roles and pick Show as collection association.
If you want to show more advanced associations here is an addin for Visual studio from CodePlex.

Populate DTO from several queries

I have a DTO with 40+ properties. But in order to populate all properties I need to execute 4 separate queries. My first query is in charged of getting basic information. For each row returned I run 3 more queries based on the id's given from the main query (N+1 problem). I can set use eager loading but then I'm loading thousands of objects that I don't need.
Should I split my DTO and create a separate DTO for each query I run then link then tie them all together into a central DTO by id?
I was envisioning a final DTO like this.
public class FooDto
{
public string Foo { get; set; }
public string Bar { get; set; }
public FirstDto FirstQueryResults { get; set; }
public SecondDto SecondQueryResults { get; set; }
public ThirdDto ThirdQueryResults { get; set; }
}
Is there a better way of solving this? I'm using Oracle and NHibernate doesn't support multi criterias. Note that I am joining most of my data. The problem comes when I need to query data with a complete new set of criteria.
How about creating a VIEW that joins the data to give the 40 properties all in one go, and basing your DTO on that - whatever a DTO may be ;-)

Resources