How to assign userId on serenity MVC framework - asp.net-mvc

I want to save CreatedBy and LastModifiedBy field on every table. Is there base resulution on serenity?
I am getting error below when i set fld field:
Severity Code Description Project File Line Suppression State
Error CS0029 Cannot implicitly convert type 'int' to 'Serenity.Data.Int32Field'
private static MyRow.RowFields fld { get { return MyRow.Fields; } }
protected override void SetInternalFields()
{
int userId = ((UserDefinition)Authorization.UserDefinition).UserId;
fld.LastModifiedBy = userId;

fld is a reference to your entity fields (metadata), not the entity instance itself.
In SaveHandler, this.Row references to created/updated entity with new values, while this.Old references entity with old values for update (kinda similar to a SQL trigger).
So you should write Row.LastModifiedBy = userId;
FYI, instead of doing it this way in every repository, implement IUpdateLogRow (and/or InsertLogRow) interfaces in your entity and default save behaviors will fill Insert/Update UserId/Date fields automatically.
Define a base row like LoggingRow sample in Serene to avoid having to implement this interface in every entity.

Related

.NET mvc adding more then 1 entity to db

I'm trying to add several entities to the db but I get this error:
"Saving or accepting changes failed because more than one entity of type 'Schema.Domain.DataModels.ActivitySummery' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration."
public void CreateNewGeneratedSchema(List<WeekDayViewModel> weekDays, int userId)
{
List<ActivitySummery> savedActivities = _schemaRepository.GetAllActivitySummeries(userId).ToList();
foreach(ActivitySummery activitySummery in savedActivities)
{
_schemaRepository.DeleteActivitySummery(activitySummery.ActivitySummeryId);
}
foreach (WeekDayViewModel weekDay in weekDays)
{
foreach (ActivitySummeryViewModel activitySummeryViewModel in weekDay.ActivitiySummeries)
{
try
{
ActivitySummery activitySummery = new ActivitySummery()
{
ActivityId = activitySummeryViewModel.ActivityId,
WeekDayId = activitySummeryViewModel.WeekDayId,
//Change userId
UserId = 1,
StartTime = activitySummeryViewModel.StartTime,
EndTime = activitySummeryViewModel.EndTime,
ActivityDescription = activitySummeryViewModel.Description,
Activity = _schemaRepository.GetSpecificActivity(activitySummeryViewModel.ActivityId),
WeekDay = _schemaRepository.GetSpecificWeekDay(activitySummeryViewModel.WeekDayId)
};
_schemaRepository.CreateActivitySummery(activitySummery);
}
catch (Exception)
{
throw new Exception("Something went wrong when trying to save the activity summery");
}
}
}
_schemaRepository.Save();
_schemaRepository.Dispose();
}
I know one solution that might work and it's to save and dispose the _schemaRepository after every time i added one model to the db and create a new instace of _schemaRepository. But im not sure if that is the right way. I know that every model that im trying to save has the pk of 0 and i think that might be the problem. However it still works and the db accepts the new entities but I still get the exception.
If your model (which you didn't show) has the primary key as ActivityId (which you also didn't indicate) and it is setup to auto-generate the primary key:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ActivityId { get; set; }
Then you must not include the primary key in the CreateActivitySummery method (also which you haven't provided).
// Remove this line...
// ActivityId = activitySummary.ActivityId;
Do note that a (reasonable) alternative to having the database generate the primary key automatically is to use Guid/UniqueIdentifier without using DatabaseGenerated. Then your application code can use Guid.NewGuid to generate new (presumably unique) primary keys that it can insert with no problem and track related entities easily.

Exclude property from updating when SaveChanges() is called

There appears to be two ways to update a disconnected Entity Framework entity using the "attach" method.
Method One is to simply set the disconnected entity's state as modified:
myDbContext.Dogs.Attach(dog);
myDbContext.Entry(dog).State = EntityState.Modified;
myDbContext.SaveChanges();
This will save all fields on the "dog" object. But say you are doing this from an mvc web page where you only allow editing of Dog.Name, and the only Dog property contained on the page is Name. Then one could do Method Two:
myDbContext.Dogs.Attach(dog);
myDbContext.Entry(dog).Property(o => o.Name).CurrentValue = dog.Name;
myDbContext.Entry(dog).Property(o => o.Name).IsModified = true;
myDbContext.SaveChanges();
Method Two could get quite verbose when there are a lot of properties to update. This prompted me to attempt Method Three, setting IsModified = false on the properties I don't want to change. This does not work, throwing the runtime error "Setting IsModified to false for a modified property is not supported":
myDbContext.Dogs.Attach(dog);
myDbContext.Entry(dog).State = EntityState.Modified;
myDbContext.Entry(dog).Property(o => o.Owner).IsModified = false;
myDbContext.SaveChanges();
I'd much prefer to use Method One everywhere, but there are many instances where my asp.net mvc view does not contain every scalar property of the Dog class.
My questions are:
Are there any attributes I could use on the POCO class that would tell Entity Framework that I never want the property to up updated? Eg, [NeverUpdate]. I am aware of the [NotMapped] attribute, but that is not what I need.
Failing that, is there any way I can use Method One above (myDbContext.Entry(dog).State = EntityState.Modified;
) and exclude fields that I don't want updated?
P.S. I am aware of another way, to not use "attach" and simply fetch a fresh object from the database, update the desired properties, and save. That is what I am doing, but I'm curious if there is a way to use "attach," thus avoiding that extra trip to the database, but do it in a way that is not so verbose as Method Two above. By "fetch a fresh object" I mean:
Dog dbDog = myDbContext.Dogs.FirstOrDefault(d => d.ID = dog.ID);
dbDog.Name = dog.Name;
myDbContext.SaveChanges();
The following may work works.
myDbContext.Dogs.Attach(dog);
myDbContext.Entry(dog).State = EntityState.Modified;
var objectContext = ((IObjectContextAdapter) myDbContext).ObjectContext;
foreach (var entry in objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(entity => entity.Entity.GetType() == typeof(Dogs)))
{
// You need to give Foreign Key Property name
// instead of Navigation Property name
entry.RejectPropertyChanges("OwnerID");
}
myDbContext.SaveChanges();
If you want to do it in a single line, use the following extension method:
public static void DontUpdateProperty<TEntity>(this DbContext context, string propertyName)
{
var objectContext = ((IObjectContextAdapter) context).ObjectContext;
foreach (var entry in objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(entity => entity.Entity.GetType() == typeof(TEntity)))
{
entry.RejectPropertyChanges(propertyName);
}
}
And use it like this
// After you modify some POCOs
myDbContext.DontUpdateProperty<Dogs>("OwnerID");
myDbContext.SaveChanges();
As you can see, you can modify this solution to fit your needs, e.g. use string[] properties instead of string propertyName as the argument.
Suggested Approach
A better solution would be to use an Attribute as you suggested ([NeverUpdate]). To make it work, you need to use SavingChanges event (check my blog):
void ObjectContext_SavingChanges(object sender, System.Data.Objects.SavingChangesEventArgs e)
{
ObjectContext context = sender as ObjectContext;
if(context != null)
{
foreach(ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
var type = typeof(entry.Entity);
var properties = type.GetProperties();
foreach( var property in properties )
{
var attributes = property.GetCustomAttributes(typeof(NeverUpdateAttribute), false);
if(attributes.Length > 0)
entry.RejectPropertyChanges(property.Name);
}
}
}
}
// Check Microsoft documentation on how to create custom attributes:
// http://msdn.microsoft.com/en-us/library/sw480ze8(v=vs.80).aspx
public class NeverUpdateAttribute: SystemAttribute
{
}
//In your POCO
public class Dogs
{
[NeverUpdate]
public int OwnerID { get; set; }
}
Warning: I did not compile this code. I'm not at home :/
Warning 2: I have just read the MSDN documentation and it says:
ObjectStateEntry.RejectPropertyChanges Method
Rejects any changes made to the property with the given name since the
property was last loaded, attached, saved, or changes were accepted.
The orginal value of the property is stored and the property will no
longer be marked as modified.
I am not sure what its behavior would be in the case of attaching a modified entity. I will try this tomorrow.
Warning 3: I have tried it now. This solution works. Property that is rejected with RejectPropertyChanges() method are not updated in the persistence unit (database).
HOWEVER, if the entity that is updated is attached by calling Attach(), the current context remains dirty after SaveChanges(). Assume that the following row exists in the database:
Dogs
ID: 1
Name: Max
OwnerID: 1
Consider the following code:
var myDog = new Dogs();
myDog.ID = 1;
myDog.Name = Achilles;
myDog.OwnerID = 2;
myDbContext.Dogs.Attach(myDog);
myDbContext.Entry(myDog).State = EntityState.Modified;
myDbContext.SaveChanges();
The current state of database after SaveChanges():
Dogs:
ID: 1
Name: Achilles
OwnerID: 1
The current state of myDbContext after SaveChanges():
var ownerId = myDog.OwnerID; // it is 2
var status = myDbContext.Entry(myDog).State; // it is Unchanged
So what you should do? Detach it after SaveChanges():
Dogs myDog = new Dogs();
//Set properties
...
myDbContext.Dogs.Attach(myDog);
myDbContext.Entry(myDog).State = EntityState.Modified;
myDbContext.SaveChanges();
myDbContext.Entry(myDog).State = EntityState.Detached;

Breeze registerEntityTypeCtor not working

I am working on a Hottowel project and I want to format some data passed on from database to Breeze, but it looks like the ctor is not getting registered.
What am I doing wrong?
In datacontext.js:
var manager = configureManager();
function configureManager() {
var mng = new breeze.EntityManager('breeze/data');
breeze.NamingConvention.camelCase.setAsDefault();
model.configureMetadataStore(mng.metadataStore);
return mng;
}
In model.js:
function configureMetadataStore(metadataStore) {
metadataStore.registerEntityTypeCtor
('UserInfo', null, userInfoInitializer);
}
function userInfoInitializer() {
if (this.Email == "")
this.Email = '---';
this.CreateDate = formatDateTime(this.CreateDate);
}
function formatDateTime(DateTime) {
return moment.utc(DateTime).format('DD. MM. YYYY. [у] hh:mm');
}
Datacontext has a reference to model, the data is transferred from database and appears on the screen, but is not formatted. console.log() calls from userInfoInitializer() are not appearing.
When I am constructing an entity, my constructor needs to have an entity to construct. I have not tried your above code but I believe that Breeze passes an entity in and you need to give that entity properties. Using this. MAY work but it is the first thing that stands out to me.
function userInfoInitializer(user) {
if (user.Email == "")
user.Email = "---";
2nd - What is your entity named in your model? Is it UserInfo or just User? You probably already know this but you need to make sure when you are adding a constructor you use the properly named Entity.
3rd - If you are using camelCase then you need to leave the first letter of the property lowercase. Ex . user.email and user.createDate.
Last, I can't tell if you are creating a 'createDate' in the constructor or that is being passed from your model. If it is indeed a property you are creating I would recommend making it an knockout observable or computed property. If it is coming from the database then you need to do something like
if (!user.createDate) { } //set it
Remember that all of the entities being returned from the database will be given that property, so if you have entities that already have a createDate in your example you are overriding that date. If you want to set createDate to now then I would move that into your method where you are creating the object.

Is there an equivalent of Rails ActiveRecord::Callbacks in ASP MVC?

Is there an equivalent of Rails ActiveRecord::Callbacks in ASP MVC?
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
I'm in a situation where we are not using identities for our primary key. We do this for reasons specific to our DB sharding design. Because of this we have a lookup table to find the next ID for a specific table. I'd like to automatically get this value and set it in an abstract class whenever a model is created/updated and before it is saved. I also need to update the lookup table with an incremented 'nextID' after the save is successful.
I'm open to other solutions on how to do this without callbacks as well.
So you need the callback just to increment ID in the lookup table? AFAIK there is no equivalent in ASP.NET, may be you could try with Async Controllers (http://msdn.microsoft.com/en-us/library/ee728598%28v=vs.100%29.aspx) and wait for a state change from the successful save, but I would prefer use a service specifically for this like Snowflake (https://github.com/twitter/snowflake/).
I found a solution using overrides as opposed to callbacks. It's my hope that ASP mvc adds support for callbacks as the framework continues to mature because callbacks allow for cleaner code by allowing the OnSave event to exist in the model[s] that the event is concerned with rather than the centralized DbContext class (separation of concerns).
Solution:
The SaveChanges method can be overridden in the Context Class (Entity Framework Power Tools creates the Context class is the 'Models' directory).
public override int SaveChanges()
{
// create a cache for id values in case their are multiple added entries in the dbcontext for the same entitytype
Dictionary<string, UniqueID> idCache = new Dictionary<string, UniqueID>();
IEnumerable<DbEntityEntry> changes = this.ChangeTracker.Entries();
foreach (var entry in changes)
{
//check if this is a new row (do nothing if its only a row update because there is no id change)
if (entry.State == System.Data.EntityState.Added)
{
//determine the table name and ID field (by convention)
string tableName = entry.Entity.GetType().Name;
string idField = entry.Entity.GetType().Name + "ID";
UniqueID id = null;
//if we've already looked this up, then use the cache
if (idCache.ContainsKey(tableName))
{
id = idCache[tableName];
}
//if we havn't looked this up before get it and add it to the cache
else
{
id = this.UniqueIDs.Find(tableName, idField);
//if it doesn't already exist in the lookup table create a new row
if (id == null)
{
id = new UniqueID(tableName, idField, 1);
// since this is a new entry add it
this.UniqueIDs.Add(id);
}
else
{
// set the state to modified
this.Entry(id).State = System.Data.EntityState.Modified;
}
}
entry.CurrentValues[tableName + "ID"] = id.NextID;
id.NextID = id.NextID + 1;
}
}
return base.SaveChanges();
}

Creating history table using Entity Framework 4.1

I am working on asp.net MVC 3 application and I am using codeFirst approach. I am trying to create history table or user table, Where I want to keep track of what columns were modified by user. How can I do this using EF Code First.
Do I need to do it after DataContext.savechanges ?
Please suggest.
Thanks.
The DbContext has a method called Entry<T>:
var entity = context.Items.Find(id);
entity.Name = "foobar";
var entry = context.Entry<Item>(entity);
entry will be of type DbEntityEntry<T> and has the properties OriginalValues and CurrentValues.
You could probably write something that will generically inspect these properties to see what has changed and then automatically insert a new record into your history table.
Either that, or use database triggers.
I'm not sure if this is really the "appropiate" way to do it, but this is how its usually done in sql:
Create an extra property version of type int or something.
Because you probably do not want to loop every time, add another property IsLatestVersion of type bool
When an entity is saved, check if the entity already exists. If so, set the entity on IsLatestVersion = false.
Increment the version, and save the changes as new entity.
Sounds to me like you want an a filter that inherits from ActionFilterAttribute. In my case, this is the simplest example that I have. This is my model, notice that the attributes dictate the mapping to the database.
[Table("UserProfile")]
public class UserProfile
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
In my case, it was as simple as the following, although it was not historical:
public sealed class UsersContext : DbContext
{
public UsersContext() : base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
LazyInitializer.EnsureInitialized(ref _initializer, ref isInitialized, ref initializerLock);
}
public void CheckDatabase()
{
Database.SetInitializer<YourDBContextType>(null);
using (var context = new YourDBContextType())
{
if (!context.Database.Exists())
{
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
// Uses your connection string to build the following table.
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
The end result is not only EF being code first, but also allows for your models for your views to use primitives derived from your complex entities. Now, if you have another, lets say historical, DBContext then I would recommend modifying either the text transformation file or creating a base class for your entities. Both ways allow for an easy generation of code that could insert into your table, then follow up with that entity, clone it into a historical model and save. All that being said, I am a fan of database first approaches with concentration on constraints, triggers, etc. instead of a framework.

Resources