ASP.NET Tutorial : Data Annotations in .NET

Leave a Comment

Data annotation is critical in modern software development for guaranteeing data integrity, readability, and clarity. Data annotations in .NET provide a standardized mechanism to transmit metadata about data objects, improving the robustness and maintainability of your code. In this article, we'll look at 25 data annotations in.NET, complete with descriptions and examples.


 What exactly are Data Annotations?

Data annotations allow developers to add metadata to data models and attributes in.NET. These annotations help to describe constraints, formatting, and validation rules, making it easier to work with data objects in a variety of scenarios, including ASP.NET applications, Entity Framework, and API validation.
'[Required]' is a required phrase.

The annotation [Required] assures that a property cannot be null. 

public class Person
{
    [Required]
    public string FirstName { get; set; }
}

2. `[StringLength]`

Defines the maximum and minimum length of a string property.

public class Product
{
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
}

3. `[Range]`

Restricts a property to a specified numeric range.

public class Temperature
{
    [Range(-40, 100)]
    public int Celsius { get; set; }
}

4. `[RegularExpression]`

Validates a property against a regular expression pattern.

public class Email
{
    [RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$")]
    public string Address { get; set; }
}

5. `[Compare]`

Compares the values of two properties for equality.

public class User
{
    public string Password { get; set; }

    [Compare("Password")]
    public string ConfirmPassword { get; set; }
}

6. `[EmailAddress]`

Ensures that a string property contains a valid email address.

public class Contact
{
    [EmailAddress]
    public string Email { get; set; }
}

7. `[Phone]`

Validates a string property as a phone number.

public class Contact
{
    [Phone]
    public string PhoneNumber { get; set; }
}

8. `[Url]`

Check if a string property contains a valid URL.

public class Website
{
    [Url]
    public string URL { get; set; }
}

9. `[CreditCard]`

Ensures a string property contains a valid credit card number.

public class Payment
{
    [CreditCard]
    public string CardNumber { get; set; }
}

10. `[MaxLength]`

Specifies the maximum length of a string property.

public class Tweet
{
    [MaxLength(280)]
    public string Text { get; set; }
}

11. `[MinLength]`

Sets the minimum length for a string property.

public class Password
{
    [MinLength(8)]
    public string Value { get; set; }
}

12. `[DataType]`

Specifies the data type of a property.

public class Person
{
    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }
}

13. `[Display]`

Customizes the display name for a property.

public class Product
{
    [Display(Name = "Product Name")]
    public string Name { get; set; }
}

14. `[ScaffoldColumn]`

Hides a property from a scaffolding in ASP.NET MVC.

public class Employee
{
    [ScaffoldColumn(false)]
    public int EmployeeID { get; set; }
}

15. `[ScaffoldTable]`

Specifies the table name for an Entity Framework Entity.

[ScaffoldTable("tbl_Product")]
public class Product
{
    public string Name { get; set; }
}

16. `[Editable]`

Determines whether a property is editable in MVC.

[Editable(false)]
public class UserProfile
{
    public string FirstName { get; set; }
}

17. `[Key]`

Marks a property as the primary key for an Entity Framework Entity.

public class Customer
{
    [Key]
    public int CustomerID { get; set; }
}

18. `[ForeignKey]`

Defines a foreign key relationship in Entity Framework.

public class Order
{
    public int CustomerID { get; set; }

    [ForeignKey("CustomerID")]
    public Customer Customer { get; set; }
}

19. `[Table]`

Specifies the table name for an Entity Framework entity.

[Table("Orders")]
public class Order
{
    public string OrderName { get; set; }
}

20. `[Column]`

Defines the column name for a property in Entity Framework.

public class User
{
    [Column("Full_Name")]
    public string FullName { get; set; }
}

21. `[ConcurrencyCheck]`

Indicates that a property should be included in optimistic concurrency checks.

public class Product
{
    [ConcurrencyCheck]
    public int UnitsInStock { get; set; }
}

22. `[Timestamp]`

Specifies that a property represents a database-generated timestamp.

public class Product
{
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

23. `[DatabaseGenerated]`

Marks a property as database-generated.

public class Order
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OrderID { get; set; }
}

24. `[NotMapped]`

Excludes a property from being mapped to the database.

public class User
{
    [NotMapped]
    public string FullName => $"{FirstName} {LastName}";
}

25. `[Bind]`

Specifies which properties should be included when binding data in an MVC action.

[Bind(Include = "FirstName, LastName, Email")]
public class UserProfile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

Conclusion

Data annotations in.NET make it simple for developers to declare metadata and limitations for data models. You can improve the dependability and readability of your code by correctly applying these annotations. These annotations are useful tools in your development toolset, whether you're building online apps with ASP.NET or working with databases in Entity Framework.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/



 

Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment