I have the following in my class and need to know how to modify the DataAnnotation to make it an identity column
public class Item
{
public Int16 ItemID { get; set; }
}
The goal is to have the EF5.0 equivalant of the SQL
ItemID smallint IDENTITY(0,1) NOT NULL,
You can use DatabaseGenerated attribute with DatabaseGeneratedOption.Identity. You can find more details about configuring EF with attributes here http://msdn.microsoft.com/en-us/data/jj591583 and about DatabaseGnerationOption enum here:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.databasegeneratedoption.aspx. You can also configure your model with Fluent API - here are some examples http://msdn.microsoft.com/en-us/data/jj591617
Related
In my request data, if I have a duplication Guid ID, I want to generate a new Guid ID automatically. How to do it?
public class Roster { public Guid Id {get; set;} }
Here Guid Id is the primary key.
When I made an api post request, what would be the value I give for Guid Id?
If you use SQL and EntityFramework Core you could use this inside your model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ActivityId { get; set; }
This will tell EF:
this property is the PRIMARY KEY of the table hence the [KEY]
this property should be automatically generated by the database
FYI you need to set a DEFAULT value for you SQL column like so:
(newsequentiaid()) tells SQL that he's in charge of creating a Globally Unique Id everytime you add a record to that table
Don't know if this is the answer you were looking for (nex time provide more info for us) anyway
hope this helps you Cheers!
UPDATE
I do not know if my solution works with MySQL i use it for SQL. Searching a bit online i found no resources to newsequentialid in MySQL database (but i could be wrong, do your own research if you'd like).
Anyway i just don't set it for example:
var activityDB = await context.Activity.FirstOrDefaultAsync(c => c.ActivityId == activity.ActivityId);
if (activityDB == null)
{
activityDB = new Activity();
context.Activity.Add(activityDB);
}
activityDB.Code = activity.Code;
activityDB.Description = activity.Description;
activityDB.Status = activity.Status;
Here's what the code does
check if my id exists if yes i have to edit if is null i don't
create new activity and edit
automatically EF nows what id to handle therefore no need to se it
If there is it means im editing for that id if not will create it automatically
I'm using Kendo grid with ForeignKey column with sorting. By default this column is sorted by value but we need it to be sorted by text. Could anyone provide please an example of doing it using ASP.NET Wrappers?
I found the trick was to implement IComparable on the foreign key object, which then sorts by the text name instead of the id in the Kendo grid:
public class MyForeignKeyModel : IComparable<MyForeignKeyModel>
{
public int ID { get; set;}
public string Name { get; set;}
public int CompareTo(MyForeignKeyModel compareTo)
{
return String.Compare(Name, compareTo.Name, StringComparison.InvariantCulture);
}
}
All the other solutions mentioned by users and Telerik look much more complicated!
Reponse by Atanas Korchev (Admin, Kendo UI) We can’t support this in all cases because the data source won’t have all data (it usually has just the foreign key which is the value)
You can use Grouping if that helps to some extend.
I have an mvc3 create page using a View Model with 2 entities
like
class ViewModel1{
public User user{get;set;}
public Company company{get;set;}
}
where User and Company are EF4 entities(tables). I need to use a single page to create both(related) tables. Now the Company entity is optional under some conditions and I use jQuery to hide the corresponding section in the view.
However since company has required fields , the post back create function has ModelState.Valid as false.
What I want to do is if the Company section is hidden, I would like to skip validating the Company entity in ViewModel in Server( I avoid validation of hidden elements in Client).
Maybe there is a better and more proper approach to this?
What you have shown is not a view model. You call it a view model but it isn't because it is referencing your EF domain entities.
A more realistic view model would look like this:
class ViewModel1
{
public UserViewModel User { get;set; }
public CompanyViewModel Company { get; set; }
}
or even flattened out and containing only the properties that your view needs:
class ViewModel1
{
public int UserId { get;set; }
[Required]
public string FullUserName { get;set; }
[Required]
public string CompanyName { get; set; }
}
Now depending on your specific requirements about view model validation your UserViewModel and CompanyViewModel classes will be specifically designed for them.
Instead of putting the entities directly in the view model, put the properties for the entities in the view model and map between the view model and the actual entity objects on the server. That way you can control what properties are required for your view. Create some custom validation rules to validate that the required company properties are there when some company information is required. To do this on the server, you can have your view model implement IValidatableObject and implement the logic in the Validate method. On the client you can add rules to the jQuery validate plugin for the "required if" properties.
public class UserCreationViewModel : IValidatableObject
{
[Required]
public string Username { get; set; }
[Required]
public string FirstName { get; set; }
...
public string CompanyName { get; set; }
public string CompanyEmail { get; set; }
public IEnumerable<ValidationResult> Validate( ValidationContext context )
{
if (!string.IsNullOrEmpty(CompanyName) && string.IsNullOrEmpty(CompanyEmail))
{
return yield new ValidationResult("Company Email is required if you specify a company", new [] { "CompanyEmail" });
}
}
}
I'm not sure what I would do on the client-side. You have a choice of either adding specific rules to the validate plugin directly, but it might be hard to make it look exactly the same as using the unobtrusive validation that MVC adds. Alternatively, you could look at adding/removing the unobtrusive attributes from the "required if" elements using jQuery depending on the state of the elements that trigger their requirement. I suggest trying both ways -- look at the docs for the validate plugin to see how to add custom rules and examine the code emitted by the MVC framework for the unobtrusive validate to see what you would need to add to make that work.
Another possibility would be including/removing a partial view with the company properties in the from based on whether the company information is required or not. That is, type in a company name and use AJAX to grab the inputs required for the company and add them to the form. If the company name is deleted, delete the elements. Leave the server-side validation the way it is, but in the partial view mimic the HTML that the framework would add in for unobtrusive validation. This is sort of the best of both worlds as the jQuery code is much simpler and you get consistent validation, too.
There are many ways you can achieve,
1) more commonly donot use [Required] attribute on Company object, but have proper validation for parameters inside Company object.
In this case if Company object is null still validation will pass, but if Company object isnot null it will validate each properties.
2) If validation involves some complex business logic, then go for Self Validating Model. (inherit from IValiddatableObject, and override Validate(...).
3) By code, in the controller.
if(model.company == null)
this.ModelState.Keys.Where(k => k.Contains("company")).ToList().ForEach(k => this.ModelState.Remove(k));
first two are best approved approaches, third is just another way to achieve your functionalities
I'm working on ASP.NET MVC 3 project using EF CodeFirst. I have a simple class with few attributes set on key column:
public class Tag
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[ScaffoldColumn(true)]
public short TagID { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
As you can see there are DatabaseGenerated(DatabaseGeneratedOption.None) and ScaffoldColumn(true) attributes. That's because I want to be able to enter the TagID manually. Now when TagControler is added to the project I don't have the TagID column shown in neither of 5 generated views.
I know I can add it manually, but I wonder if this behavior is by design or I'm doing something wrong?
Primary keys aren't scaffolded as editable fields by default. Instead there is a hidden field for the key. If you wanted to change this behavior you could modify the templates but it is by design since generally it doesn't make sense to edit the primary key of an entity.
Here is some info on how to do this if you wanted to make this change any time you added a view or wanted to make some other custom change to the scaffolding:
http://blogs.msdn.com/b/joecar/archive/2011/01/06/add-the-asp-net-mvc-3-code-templates-to-your-application-with-nuget.aspx
I have an application where the identity column is stored as an Oracle VARCHAR2(50 BYTE) but is actually a Guid. I want my model to expose it as a Guid:
class Foo
{
public Guid Id { get; set; }
}
Using Fluent NHibernate I don't see a CustomTypeIs() method on the IIdentityPart. I would think it would be something similar to an IUserType, but I can't find the correlation. Any thoughts?
Fabio Maulo noted that this is governed by the DataProvider on the NHibernate Users mailing list.