Set Somee SQL datetime italian language - sql-server

I have develop an MVC C# application, published in Somee.
Only in Somee I have a problem with datetime format (US vs IT)
I have a typed list view whit, for each row, a date field and
same record edited in a partial view.
Data Annotation class:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DataCons { get; set; }
In list view I used:
<td>#Html.EditorFor(Model => Model[c].DataCons, "{0:dd/MM/yyyy}", new { #style = "width: 140px;" })</td>
and a calendar is used and no problem with date time format
In partial view for editing record, same code used in list view doesn' t work and I need to use TextBoxFor instead EditorFor, a model binder to convert datetime format and a javascript date-picker.
#Html.TextBoxFor(m => m.Scadenza, "{0:dd/MM/yyyy}", new { #class = "date-picker", style = "width: 90px;" })
A way to unify my code maybe setting somee language setting?
Regards

Related

Dapper FluentMap: property with name 'Date' can't be mapped

I've faced the problem with Dapper FluentMap (version 1.60) which I don't know how to fix. It looks like Dapper can't map a column from a table if the corresponding property in .NET class has "Date" name.
I have the table in DB (I'm using MS SQL if that's matter) with column Dt of Date type.
There is an entity with DateTime property:
public class MyEntity {
public DateTime Date { get; set; }
}
and the corresponding mapping:
public class MyEntityMapper : EntityMap<MyEntity> {
public MyEntityMapper() {
Map(p => p.Date).ToColumn("Dt");
}
}
When I try to get data from the DB and map to MyEntity, I get the following error:
ArgumentNullException: Value cannot be null. Parameter name: meth
If I rename Date property in MyEntity to something else like Dt or JustDate - everything works fine. Is there such restriction in Dapper Fluent Map (not allowed to give a name to property equal to data type name in DB)?
If so, is it possible to overcome it somehow? Because in my case it's a bit problematic to rename property in MyEntity
Yes you are right, the only solution you can do was to change your entity property Date into other name.

Not Nullable fields in SQL Server Still Considered Required Fields in ASP.NET MVC

I have a non nullable fields in a table with default values set already in the property "Default Value or Binding" in SSMS. I linked this table in an ASP.Net mvc application. When I created the view and when running the create view, it still asking me to enter the required fields for the non nullable fields even though i assigned a default value for them.
After this I removed the line:
#Html.ValidationMessageFor(model => model.position, "", new { #class = "text-danger" })
which is bellow each
#Html.EditorFor statement, but this time it post me back to the same page with no changes in the database.
How can I get rid of the message in the required fields as I have already default value for them?
Simply you can create a constructor in your model. It will initialize default values once new instance is created. If user provides that fields, then it will be overridden. If no, value from constructor will be passed to EF.
What you are trying to do now, won't work according to specifications: https://msdn.microsoft.com/en-us/library/ms187872.aspx
Here you can see how to achieve what you want, considering that this field will always be generate in database.
This is one of the many reasons not to use entity models as viewmodels. MVC doesn't care that the required field has a default value, that information is database-related and not related to input validation.
Introduce a viewmodel where those properties are not required, and map the posted viewmodel to your entity model.
So, given an entity model that looks like this:
public class SomeEntity
{
// this property is not-nullable in the database
[Required]
public string SomeRequiredDatabaseField { get; set; }
}
Because the SomeRequiredDatabaseField is NOT NULL, it is annotated as such by Entity Framework, even if it has a default value. MVC will pick up this annotation, and consider the model not valid when the property has no value.
Now if you introduce a viewmodel, you can tell MVC that this property is not required:
public class SomeViewModel
{
// Not required
public string SomeRequiredDatabaseField { get; set; }
}
Now in your controller, you map the viewmodel to the entity model (preferably using AutoMapper):
public ActionResult Post(SomeViewModel model)
{
if (ModelState.IsValid)
{
var entityToSave = new SomeEntity
{
SomeRequiredDatabaseField = model.SomeRequiredDatabaseField
};
db.SomeEntity.Add(entityToSave);
}
// ...
}

Entity Framework 7 migration: how to get a varchar column with a length greater than 1?

I have the following:
[Table("Countries")]
public class Country
{
public int CountryId { get; set; }
[MaxLength(255), Required]
public string CountryName { get; set; }
[Column(TypeName = "varchar")]
public string CountryCode { get; set; }
}
Every time I apply my migration, CountryCode becomes a varchar column with a max length of 1. I tried setting the MaxLength annotation to 255 and still get a max length of 1. When the column is set as nvarchar it works as expected. Am I doing something wrong?
Edit: Whenever I explicitly set the string data type, length sets to 1. I could have used Column(TypeName = "nvarchar")] and the length sets as 1..
Would of liked to have used data annotations, but I was able to get it to work with:
builder.Entity<Country>()
.Property(e = e.CountryCode).HasSqlServerColumnType("VARCHAR(30)");
Data Annotations are not yet fully implemented in Entity Framework 7.
You can still add annotations to your entity classes so that they are
used by other frameworks (such as ASP.NET MVC), but Entity Framework
will not process these annotations. You can track support for Data
Annotations on GitHub.
http://ef.readthedocs.org/en/latest/modeling/configuring.html
OK using .net core 2 targeting sql server I had this issue. My model builder looked like this.
modelBuilder.Entity<StreamCheckpointDto>()
.Property(e => e.StreamName)
.HasColumnType("varchar")
.HasMaxLength(40).IsUnicode(false);
Once I removed the HasColumnType and let it choose varchar automatically based on my StreamCheckpointDto.StreamName being a string the length became 40 as expected. you might also be able to use.
.HasColumnType("varchar(40)")
instead.

DateCreated or Modified Column - Entity Framework or using triggers on SQL Server

After I read one question in attached link, I got a sense of how to set DateCreated and DateModified columns in Entity Framework and use it in my application. In the old SQL way though, the trigger way is more popular because is more secure from DBA point of view.
So any advice on which way is the best practice? should it be set in entity framework for the purpose of application integrity? or should use trigger as it make more sense from data security point of view? Or is there a way to compose trigger in entity framework? Thanks.
EF CodeFirst: Rails-style created and modified columns
BTW, even though it doesn't matter much, I am building this app using ASP.NET MVC C#.
Opinion: Triggers are like hidden behaviour, unless you go looking for them you usually won't realise they are there. I also like to keep the DB as 'dumb' as possible when using EF, since I'm using EF so my team wont need to maintain SQL code.
For my solution (mix of ASP.NET WebForms and MVC in C# with Business Logic in another project that also contains the DataContext):
I recently had a similar issue, and although for my situation it was more complex (DatabaseFirst, so required a custom TT file), the solution is mostly the same.
I created an interface:
public interface ITrackableEntity
{
DateTime CreatedDateTime { get; set; }
int CreatedUserID { get; set; }
DateTime ModifiedDateTime { get; set; }
int ModifiedUserID { get; set; }
}
Then I just implemented that interface on any entities I needed to (because my solution was DatabaseFirst, I updated the TT file to check if the table had those four columns, and if so added the interface to the output).
UPDATE: here's my changes to the TT file, where I updated the EntityClassOpening() method:
public string EntityClassOpening(EntityType entity)
{
var trackableEntityPropNames = new string[] { "CreatedUserID", "CreatedDateTime", "ModifiedUserID", "ModifiedDateTime" };
var propNames = entity.Properties.Select(p => p.Name);
var isTrackable = trackableEntityPropNames.All(s => propNames.Contains(s));
var inherits = new List<string>();
if (!String.IsNullOrEmpty(_typeMapper.GetTypeName(entity.BaseType)))
{
inherits.Add(_typeMapper.GetTypeName(entity.BaseType));
}
if (isTrackable)
{
inherits.Add("ITrackableEntity");
}
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1}partial class {2}{3}",
Accessibility.ForType(entity),
_code.SpaceAfter(_code.AbstractOption(entity)),
_code.Escape(entity),
_code.StringBefore(" : ", String.Join(", ", inherits)));
}
The only thing left was to add the following to my partial DataContext class:
public override int SaveChanges()
{
// fix trackable entities
var trackables = ChangeTracker.Entries<ITrackableEntity>();
if (trackables != null)
{
// added
foreach (var item in trackables.Where(t => t.State == EntityState.Added))
{
item.Entity.CreatedDateTime = System.DateTime.Now;
item.Entity.CreatedUserID = _userID;
item.Entity.ModifiedDateTime = System.DateTime.Now;
item.Entity.ModifiedUserID = _userID;
}
// modified
foreach (var item in trackables.Where(t => t.State == EntityState.Modified))
{
item.Entity.ModifiedDateTime = System.DateTime.Now;
item.Entity.ModifiedUserID = _userID;
}
}
return base.SaveChanges();
}
Note that I saved the current user ID in a private field on the DataContext class each time I created it.
As for DateCreated, I would just add a default constraint on that column set to SYSDATETIME() that takes effect when inserting a new row into the table.
For DateModified, personally, I would probably use triggers on those tables.
In my opinion, the trigger approach:
makes it easier; I don't have to worry about and remember every time I save an entity to set that DateModified
makes it "safer" in that it will also apply the DateModified if someone finds a way around my application to modify data in the database directly (using e.g. Access or Excel or something).
Entity Framework 6 has interceptors which can be used to set created and modified. I wrote an article how to do it: http://marisks.net/2016/02/27/entity-framework-soft-delete-and-automatic-created-modified-dates/
I agree with marc_s - much safer to have the trigger(s) in the database. In my company's databases, I require each field to have a Date_Modified, Date_Created field, and I even have a utility function to automatically create the necessary triggers.
When using with Entity Framework, I found I needed to use the [DatabaseGenerated] annotation with my POCO classes:
[Column(TypeName = "datetime2")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Date_Modified { get; set; }
[Column(TypeName = "datetime2")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Date_Created { get; set; }
I was attempting to use stored procedure mapping on an entity, and EF was creating #Date_Modified, #Date_Created parameters on my insert/update sprocs getting the error
Procedure or function has too many arguments specified.
Most of the examples show using [NotMapped], which will allow select/insert to work, but then those fields will not show up when that entity is loaded!
Alternately you can just make sure any sprocs contain the #Date_Modified, #Date_Created parameters, but this goes against the design of using triggers in the first place.

ASP.NET MVC dropdownlist with entity framework

I'm new to asp.net mvc and the entity framework and i'm trying to make a dropdownlist with data out of my database. I have the following:
Controler:
//
// GET: /StoreEditor/Edit/(ID)
public ActionResult Edit(int id)
{
StoreEditorViewModel data = new StoreEditorViewModel(id);
return View(data);
}
ViewModel:
public StoreEditorViewModel(int id)
{
using (MvcTicketsEntities storeDB = new MvcTicketsEntities())
{
details = (from t in storeDB.Tickets.Include("Artists").Include("Genres")
where t.TicketId == id
select t).FirstOrDefault();
}
}
Now i get get all my labels and editors in de view. But how do i make a dropdownlist with all the names in the database table GENRES in the field NAME.
The table GENRES has 2 fields GenreId and Name.
Please refer to the below link:
http://codeclimber.net.nz/archive/2009/08/10/how-to-create-a-dropdownlist-with-asp.net-mvc.aspx
This explains quite well, how to approach it.
Basically, you would need to create List<SelectListItem> object and supply it to the dropdown list.
Thanks

Resources