Attribute that will mark all non nullable fields as Required - c#

I have dto with several fields
For example
public class SupplierModel
{
public string SupplierNameNormalized { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
}
I want to write attribute [MarkNonNullablePropertiesAsRequired] to mark all fields as required, so swagger can show them as required when project, launched.
I created class for attribute
[AttributeUsage(AttributeTargets.Class)]
public class MarkNonNullablePropertiesAsRequired: Attribute
{
}
How I can do this correctly and what I need to write inside class?

Related

Map one Class properties to two different class properties using Mapster

I have 3 classes with the name of Employee, EmployeeTwo, and EmployeeThree, I wanted to map Employee to EmployeeTwo and Employee to EmployeeThree.
Following are the Classes.
I also have tried to define the AdaptMember attribute on the Employee Class property but it only defines one and I have to map it with two different.
Note: I cannot define any attribute to the EmployeeTwo and EmployeeThree classes because this comes from the API and it can be regenrate.
public class Employee
{
[AdaptMember(nameof(EmployeeTwo.EmployeeID))]
public int ID { get; set; }
[AdaptMember(nameof(EmployeeTwo.EmployeeName))]
public string Name { get; set; }
}
public class EmployeeTwo
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
public class EmployeeThree
{
public int EmployeeThreeID { get; set; }
public string EmployeeThreeName { get; set; }
}
Any help is really appriciated.
As I understand you, you want to make a custom object mapping using mapster.
If you want to make a custom mapping you need to create a class:
using Mapster;
namespace Application.Mapsters
{
public class Config : ICodeGenerationRegister
{
public void Register(CodeGenerationConfig config)
{
TypeAdapterConfig<Employee, EmployeeTwo>
.NewConfig()
.Map(dst => dst.EmployeeID, src => src.ID)
.Map(dst => dst.EmployeeName, src => src.Name);
}
}
}
For instance, follow this example to see how to make a custom mapping using mapster:
https://floatincode.net/2021/07/26/mapster-generate-dto-async-after-map-actions-dependency-injection/

How to update(by merging) edmx without override the model classes in asp.net mvc

I am developing an application in asp.net mvc. I use entity framework as ORM. I have a problem. To use javascript unobstrusive validation, I need to add annotation to model objects. For example; [Required], [EMailAddress]. But when we add something to the database and update it, all model classes are override, and all annotations disappear. Or, as soon as you open edmx, automatic model classes are automatically override. How can I solve this problem. There are dozens of screens and classes, the slightest change in edmx erases the annotation in all classes, causing huge waste of time.
// <auto-generated>
using System.ComponentModel.DataAnnotations;
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Surveys
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Surveys()
{
this.SurveyQuestions = new HashSet<SurveyQuestions>();
this.SurveyCustomers = new HashSet<SurveyCustomers>();
}
public int SurveyId { get; set; }
[Required(ErrorMessage = "Plase enter survey name.")]
public string SurveyName { get; set; }
[Required(ErrorMessage = "Please enter survey description.")]
public string SurveyDescription { get; set; }
// [DataType(DataType.Date)]
public System.DateTime? CreatedDate { get; set; }
//[DataType(DataType.Date)]
public System.DateTime? UpdatedDate { get; set; }
public int CreatedUserId { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SurveyQuestions> SurveyQuestions { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SurveyCustomers> SurveyCustomers { get; set; }
public string Token { get; set; }
}
}
Editted for
Metadata
Surveys Partial & Metadata
//PartialClass
[MetadataType(typeof(SurveyMetadata))]
public partial class Surveys
{
}
//Metadata
public partial class SurveyMetadata
{
public int SurveyId { get; set; }
[Required(ErrorMessage = "Lütfen anket adını giriniz.")]
public string SurveyName { get; set; }
[Required(ErrorMessage = "Lütfen anket açıklamasını giriniz.")]
public string SurveyDescription { get; set; }
// [DataType(DataType.Date)]
public System.DateTime? CreatedDate { get; set; }
//[DataType(DataType.Date)]
public System.DateTime? UpdatedDate { get; set; }
public int CreatedUserId { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public virtual ICollection<SurveyQuestionMetadata> SurveyQuestionMetadatas { get; set; }
public virtual ICollection<SurveyCustomerMetadata> SurveyCustomerMetadatas { get; set; }
public string Token { get; set; }
}
GetData Ajax Event
// GET: Survey
public ActionResult GetData()
{
using (MerinosSurveyEntities entity = new MerinosSurveyEntities())
{
List<Surveys> surveys = entity.Surveys.Where(x => x.IsActive && x.Status)
.OrderBy(x => x.SurveyId).ToList();
return Json(new { data = surveys }, JsonRequestBehavior.AllowGet);
}
}
How I should change my GetData event.And what list should go to the client side??
Best Practice is, use ViewModel[Not Entity/Model classes] to manipulate / play at Client Side.
So use ViewModel, Inherit Model classes and then use Annotations
For eg.
Public class ViewModelClass: ModelClass
{
[Required("First Name is Required")]
Public String FirstName {get; set;}
}
For do such thing you can use partial classes and use "ModelMetadataType" in .net core annotation above your class.
lets do it in code:
this is your model that is created in edmx:
public partial class Student{
public string FirstName {get; set;}
}
first of all you have to create a partial class in another file with same name as student class and be careful its name space should be same as above class. (classes must be out of edmx file)
[ModelMetadataType(typeof(StudentMetaData))]
public partial class Student{
}
and at the end you must create your metadata class like this:
public class StudentMetaData{
[Display(name="First Name")]
public string FirstName {get; set;}
}
now you can update your edmx file without changing the data annotations in your metadata classes.
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.metadatatypeattribute?view=netframework-4.8
Working from memory at the moment, but the EF classes are always partial so create another partial implementation of the same class, then add the Interface and Metadatatype binding to that.
// Entity Framework Model
public partial class User
{
public string Email { get; set; }
public string Password { get; set; }
}
// Your Interface with data annotations
public interface IUser
{
[Required]
string Email { get; set; }
[Required]
string Password { get; set; }
}
// Partial Model appling the interface to the entity model
[MetadataType(typeof(IUser))]
public partial class User : IUser
{
}
Under this approach, in the future, you only need to worry about updating your interface should you add new properties
Copy the generated CS files (the one's with your table names) that you've already added your annotations to, to another folder, then overwrite the newly generated ones, I do it this way and shall continue to until there's a more hassle-free way to do it.

How to use TinyMCE with entity framework entities

I have entity class in created using entity framework which is in my Domain project
using System;
using System.Collections.Generic;
public partial class Test
{
public int Id { get; set; }
public int ExamID { get; set; }
public string TestName { get; set; }
public string StartDescription { get; set; }
public string EndDescription { get; set; }
}
And In my MVC application I am creating one viewmodel which I use in my view
public class TestViewModel
{
public Test Test { get; set; }
}
Now I want to make fields related to "StartDescription" and "EndDescription", for this is am trying to use TinyMCE.
Now the problem is "[AllowHtml]" attribute is in mvc but my real entity is in other project
I am following this tutorial.
http://www.codeproject.com/Articles/674754/TinyMCE-and-ASP-NET-MVC-advanced-features
Rather than your view model having an instance of Test it should contain the properties you wish to use in the view. You can then add the [AllowHtml] attribute to the properties in your view model without affecting your domain objects.
public class TestViewModel
{
public int Id { get; set; }
[AllowHtml]
public string StartDescription { get; set; }
[AllowHtml]
public string EndDescription { get; set; }
}
In your controller you would then need to map the view model to your domain class.
Old post but thought this might be relevant for someone else:
borrowing a sample code from petelids and modifying it.
public class TestViewModel
{
public int Id { get; set; }
[UIHint("tinymce_jquery_full"), AllowHtml]
public string StartDescription { get; set; }
[UIHint("tinymce_jquery_full"), AllowHtml]
public string EndDescription { get; set; }
}
Providing the UIHint on the model object you can place your tinyMCE script code in a file saved in the Folder
~/Views/Shared/TemplateEditor
I do this using the TinyMCE4.MVC libraries - however mine is modified a bit for my own special workings that I have added.

EF Code First: Trying to get a child property's parameters to appear in the parent class' table

I have a class, "Search". See definition below:
public class Search
{
[Key]
public int SearchID { get; set; }
public int UserID { get; set; }
public SearchParameters SearchParameters { get; set; }
public ICollection<SearchProvider> SearchProviders { get; set; }
public User User;
}
SearchParameters is a class with value types, and a few sub-classes; as defined below:
public class SearchParameters
{
public List<string> SearchTerms { get; set; }
public int MaxRecords { get; set; }
public DistanceParameter Distance { get; set; }
public PriceRangeParameter PriceRange { get; set; }
}
The idea is that I do not want a separate SearchParameters table that has to link to the Search table because every property of the search is always one to one (Except for SearchTerms). Really, what I want EF to do is 'bring up' the child classes' properties so we end up with All the properties of SearchParameter in the SearchTable (and all the parameters of the DistanceParameter and PriceRangeParameter objects themselves). What annotations or other logic would I need for this to work? Thanks!
I think EF Complex Type mapping is what you need, see more here:
http://weblogs.asp.net/manavi/archive/2011/03/28/associations-in-ef-4-1-code-first-part-2-complex-types.aspx

How to set order of appearance for fields when using Html.EditorFor in MVC 2?

I have the following classes in my Model:
public abstract class Entity : IEntity
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required,StringLength(500)]
public string Name { get; set; }
}
and
public class Model : SortableEntity
{
[Required]
public ModelType Type { get; set; }
[ListRequired]
public List<Producer> Producers { get; set; }
public List<PrintArea> PrintAreas { get; set; }
public List<Color> Colors { get; set; }
}
To display the "Model" class in the view I simply call Html.EditorFor(model=>model), but the "Name" property of the base class is rendered last, which is not the desired behaviour.
Is it possible to influenece on the order of displayed fields somehow?
I've not been able to find an attribute for that, so your options are:
1) create one, and then revise the base Object.ascx template to account for it, or
2) create a custom editor template for your classes that explicitly put stuff in the order you want.

Categories