Store read-only calculated field with Entity Framework Code First - ef-code-first

I am using Entity Framework Code First, and I have an entity defined with a StartTime property, an EndTime property and a Duration property (along with some others). The Duration property is a calculated field and it is the duration in minutes between the start and end time. My property declarations are shown below:
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public int Duration
{
get
{
return (int)this.EndTime.Subtract(this.StartTime).TotalMinutes;
}
}
I would like to run this calculation in code, but have the duration value persisted to the database along with the start and end time values (to make it easier later down the line when I come to run reports against these figures).
My question is, how can I get this read-only property to map back and save to the database using code first?

Inspired by Slauma's answer, I was able to achieve what I was aiming for by using a protected setter. This persisted the value back to the database but didn't allow the value to be modified elsewhere.
My property now looks like this:
public int Duration
{
get
{
return (int)this.EndTime.Subtract(this.StartTime).TotalMinutes;
}
protected set {}
}

Supplying an empty setter might be a possible solution (although then the property isn't readonly anymore, of course):
public int Duration
{
get
{
return (int)this.EndTime.Subtract(this.StartTime).TotalMinutes;
}
set { }
}
As far as I know, readonly properties are not mappable to a column in the database.

Related

Audit.net data models example

Does any one have a working example of how to added audit models to an existing project, for Audit.Net.
It is one fantastic component to use, and up until now, my team and I have gotten by with the standard JSON files, however, we'd like to migrate our current solution to our Xamarin application, and would like to store the auditing in the local SQLite database on the device.
However, the documentation for this project is somewhat lacking and there is no concise examples of how to get custom auditing working with Entity Framework.
We have worked through the MD files on the github repo, but we still cannot get auditing to work.
Another question, similar to this has been asked HERE, but there is no definitive example of what the Audit_{entity} table should look like, what fields it MUST contain, and how to set up relationships for it.
We tried to reverse engineer the JSON files into a relational structure, but at the time of asking this question, we have not gotten any auditing to write to the SQLite database.
Sorry about the documentation not helping too much, hope I (or anybody) can provide better documentation in the future.
I am assuming you are using EntityFramework to map your entities
to a SQLite database, and you want to use the EF data
provider
to store the audits events in the same database, in Audit_{entity} tables.
There is no constraint on the schema you want to use for your Audit_{entity} tables, as long as you have a one-to-one relation between your {entity} table and its Audit_{entity} table. Then the mapping can be configured on several ways.
The recommendation for the Audit_{entity} tables is to have the same columns as the audited {entity} table, with any common additional column needed, like a User and a Date defined on an Interface.
So, if all your Audit_{entity} tables has the same columns/properties as its {entity}, and you added some common columns (defined on an interface), the configuration can be set like this:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Audit_User : IAudit
{
public int Id { get; set; }
public string Name { get; set; }
// IAudit members:
public string AuditUser { get; set; }
public datetime AuditDate { get; set; }
public string Action { get; set } // "Insert", "Update" or "Delete"
}
Audit.Core.Configuration.Setup()
.UseEntityFramework(x => x
.AuditTypeNameMapper(typeName => "Audit_" + typeName)
.AuditEntityAction<IAudit>((ev, ent, auditEntity) =>
{
auditEntity.AuditDate = DateTime.UtcNow;
auditEntity.AuditUser = evt.Environment.UserName;
auditEntity.AuditAction = ent.Action;
});
Note the interface is not mandatory, but using it makes the configuration cleaner. Also note you can make your Audit_{entity} inherit from your {entity} if you wanted to.
Update
Maybe my assumption at the beginning is incorrect and you are not auditing EF entities, but any other type of audit. If that's the case, what you are looking for is a Data Provider that stores the audit events into your SQLite database.
At the time being, there is no built-in data provider that stores to SQLite, and if there was one, it would store just the JSON representation of the event in one column (like the SQL/MySql providers). But it looks like you want to have a custom schema, so you will need to implement your own data provider.
Check the documentation here.
Here is a sample skeleton of a data provider:
public class SQLiteDataProvider : AuditDataProvider
{
public override object InsertEvent(AuditEvent auditEvent)
{
// Insert the event into SQLite and return its ID
}
public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
{
// Replace the event given its ID (only used for CreationPolicies InsertOnStartReplaceOnEnd and Manual)
}
// async implementation:
public override async Task<object> InsertEventAsync(AuditEvent auditEvent)
{
// Asynchronously insert the event into SQLite and return its ID
}
public override async Task ReplaceEventAsync(object eventId, AuditEvent auditEvent)
{
// Asynchronously replace the event given its ID
}
}
Then you just set it up with:
Audit.Core.Configuration.Setup()
.UseCustomProvider(new SQLiteDataProvider());

ASP.NET setting and getting viewstate in a property

can someone please explain me the code written below
public IList<GetProductPrice> CurrentPage
{
get { return ViewState["CurrentPage"] as List<GetProductPrice>; }
set { ViewState["CurrentPage"] = value; }
}
It is called a Property. They generate a getter and setter functions when compiled:
List<GetProductPrice> GetCurrentPage(){
return ViewState["CurrentPage"] as List<GetProductPrice>;
}
void SetCurrentPage(List<GetProductPrice> value) {
ViewState["CurrentPage"] = value;
}
//i think its actual get_.. but it doesn't matter for the example
So its generates ease of use getter setters. which you can just call by using:
var test = CurrentPage; //compiled to var test = GetCurrenctPage();
CurrentPage = test; //compiled to SetCurrentPage(test);
If you leave the getter and setter empty like this:
public int CurrentPage
{
get;
set;
}
it will also generate a backing field on the class where it stores the data:
private int _currentPage;
public GetCurrentPage(){ return _currentPage }
public SetCurrentPage(int value) { _currentPage = value }
Why do we do this?
Using getters and setters is a very old best practise from java (where ide's would have an option to generate them). But this would lead to a lot of boilerplate code!
In C# they try to counter this by adding these properties. But why do we need getters and setters? For example if you want to be notified when a value changes (to mark the classes it self as dirty). I think entity framework uses it to track if a model is changed otherwise it wont do a db update call. There are also other usefull tools that inject code in properties on compile time. to add extra functionality.
How not to use it:
using properties to return HttpContext.Current Is a dangerous one because you secretly depend on the HttpContext so try not to do this at any time!
Generally its also bad practise to use it when the code inside the get or set is very heavy (very instensive). Its bad practise because someone else using the code might think he is just setting a property/field while actually some very heavy code is executed. its best practice to make a special function for this instead and private the getter/setter:
public int Property {get; private set; }
public SetProperty(int value){
//intensive code here:
Property = value;
}
This property is letting the consumer of the property to use it like Local collection without referring the ViewState in the code. It will make the code simple and easy to use.
get { return ViewState["CurrentPage"] as List<GetProductPrice>; }
Here the ViewState object ViewState["CurrentPage"] is converted to list of GetProductPrice
set { ViewState["CurrentPage"] = value; }
Here the List is assigned to ViewState["CurrentPage"]
This code will only work in a controller, where ViewState is a property. This CurrentPage property provides a statically-typed way to access a certain ViewState item through that property.
So instead of sprinkling ViewState["CurrentPage"] as List<GetProductPrice> all over your controller code where you want to access the "current page", you can now simply use the CurrentPage property.
Of course "current page" is a term made up by the developer who chose to name things like this, I don't see how a List<GetProductPrice> has a relation to the "current page".

Definining specific mapping rule for a field

I've started using ORMLite two days ago for refactoring an existing app....
I've some old stored procedure that returns columns with name that don't map 1:1 my dto object but I've managd to use [AliasAttribute] and it works fine.... at the same time I've some column that currently are mapped with some logic... for example
//Consider I've a dataset and I'm processing rows
int average = (int)row["AVERAGE"];
if(average > 50)
{
myDTO.Message = "Warning";
}
else
{
myDTO.Message = "OK";
}
Now we all agree it's not what it should be done at DataLayer but on that 5years old application we do so...is there a way I can tell in my DTO class (as I've done for Alias) to tell how to act when mapping the AVERAGE column?
Another question do ORM performs a trim on string or have I to perform it myself? again on some SP I've got no trim and I get something as "John DOE " ....now I do a .TrimEnd() when I got the value...
Thanks
Add the message as a property on your dto
public class MyDto
{
public int Average { get; set; }
public string Message
{
get { return Average > 50 ? "Warning" : "OK"; }
}
}

Can you override Date.Now or Date.Today for debugging purposes in an ASP.NET web application?

We have a very massive system where reports are run off dates from specific days through to today's date using various definitions of "GenerateSalesReport(DateStart, Date.Now)".
For debugging purposes, I want to simulate reports that occurred in the past so I need to change the object "Date.Now" to a specific date from the past on my development environment. Is it possible to override date.Now?
That is one of the failings of DateTime.Now and related functions.
You should be passing in a DateTime to any function that relies on it. Any place you use DateTime.Now or DateTime.Today (and such) is a place where you should be passing in the date.
This allows you to test for different DateTime values, will make your code more testable and remove the temporal dependency.
A good solution is to abstract away external dependencies to be able to be able to stub them during test. To virtualize time I often use something like this:
public interface ITimeService {
DateTime Now { get; }
void Sleep(TimeSpan timeSpan);
}
In your case you don't need the Sleep part since you only depend on the current time, and of course you need to modify your code to use an externally supplied ITimeService when the current time is required.
Normally you would use this implementation:
public class TimeService : ITimeService {
public DateTime Now { get { return DateTime.Now; }
public void Sleep(TimeSpan timeSpan) { Thread.Sleep(timeSpan); }
}
For testing purposes you can instead use this stub:
public class TimeServiceStub : ITimeService {
public TimeServiceStub(DateTime startTime) { Now = startTime; }
public DateTime Now { get; private set; }
public void Sleep(TimeSpan timeSpan) { Now += timeSpan; }
}
Even if this were possible, you'd probably be better off changing the system time. Otherwise you've created a whole new test case (where your system is running under a different time than every other process on the system). Who knows what kind of problems you could run into.

ASP.NET; Several session variables or a "container object"?

I have several variables that I need to send from page to page...
What is the best way to do this?
Just send them one by one:
string var1 = Session["var1"] == null ? "" : Session["var1"].ToString();
int var2 = Session["var2"] == null ? 0 : int.Parse(Session["var2"].ToString());
and so on...
Or put them all in some kind of container-object?
struct SessionData
{
public int Var1 { get; set; }
public string Var2 { get; set; }
public int Var3 { get; set; }
}
--
SessionData data = Session["data"] as SessionData;
What is the best solution? What do you use?
A hybrid of the two is the most maintainable approach. The Session offers a low-impedance, flexible key-value pair store so it would be wasteful not to take advantage of that. However, for complex pieces of data that are always related to each other - for example, a UserProfile - it makes sense to have a deeply nested object.
If all the data that you're storing in the Session is related, then I would suggest consolodating it into a single object like your second example:
public class UserData
{
public string UserName { get; set; }
public string LastPageViewed { get; set; }
public int ParentGroupId { get; set; }
}
And then load everything once and store it for the Session.
However, I would not suggest bundling unrelated Session data into a single object. I would break each seperate group of related items into their own. The result would be something of a middleground between the two hardline approaches you provided.
I use a SessionHandler, which is a custom rolled class that looks like this
public static class SessionHandler
{
public static string UserId
{
get
{
return Session["UserId"];
}
set
{
Session["UserId"] = value;
}
}
}
And then in code I do
var user = myDataContext.Users.Where(u => u.UserId = SessionHandler.UserId).FirstOrDefault();
I don't think I've every created an object just to bundle other objects for storage in a session, so I'd probably go with the first option. That said, if you have such a large number of objects that you need to bundle them up to make it easier to work with, you might want to re-examine your architecture.
I've used both. In general, many session variable names leads to a possibility of collisions, which makes collections a litte more reliable. Make sure the collection content relates to a single responsibility, just as you would for any object. (In fact, business objects make excellent candidates for session objects.)
Two tips:
Define all session names as public static readonly variables, and make it a coding standard to use only these static variables when naming session data.
Second, make sure that every object is marked with the [Serializable] attribute. If you ever need to save session state out-of-process, this is essential.
The big plus of an object: properties are strongly-typed.

Resources