sarpay
7/31/2018 - 9:10 AM

EF DB Model

To avoid classes to be converted to tables;

  1. Make sure you do not expose a DbSet in your DbContext-derived class
  2. Make sure you do not have any mention of HairCutStyle in your OnModelCreating override
  3. Mark your HairCutStyle property using the NotMapped attribute.

To Create a full audited table

with fields; deletion, modification, creation times, deleter / creator / modifier user ids

public class AgentCommissionProtocolTarget : FullAuditedEntity
{
    
}

Set custom db names and fields

[Table("AgentCommProtocolTarget")]
public class AgentCommissionProtocolTarget : Entity
{
  [DataType(DataType.PhoneNumber)]
  public decimal TargetStart { get; set; }
}

Create Composite Unique Indexes

[Index("IX_EventKeyAndType", 0, IsUnique = true)]
[Required]
[MaxLength(20)]
public string EventKey { get; set; }

[Index("IX_EventKeyAndType", 1, IsUnique = true)]
[Required]
[MaxLength(10)]
public string Type { get; set; }

Create Composite Primary Key

[Key, Column(Order = 0)]
[MaxLength(20)]
public string EventKey { get; set; }

[Key, Column(Order = 1)]
[MaxLength(10)]
public string Type { get; set; }

Create 1 to many relationship w/ foreign key

/* Case 1: PK is Identity */
public class OneTable
{
  [CanBeNull]
  // [JsonIgnore] use to ignore reference looping for JSON.NET
  // [IgnoreDataMember] use to ignore reference looping for XmlDCSerializer
  public virtual ICollection<ManyTable> Manies { get; set; }
}
public class ManyTable
{
  /* auto creates foreign key for identity PKs */
}
  
// -- or --

/* Case 2: PK is NOT Identity */
public class Product : Entity<string>
{
  [MaxLength(3)]
  public override string Id { get; set; }
  
  // [JsonIgnore] use to ignore reference looping for JSON.NET
  // [IgnoreDataMember] use to ignore reference looping for XmlDCSerializer
  public virtual ICollection<Plan> Plans { get; set; }
}

public class Plan : Entity
{
  [ForeignKey("Product"), MaxLength(3)]
  public string ProductId { get; set; }
  public Product Product { get; set; }
  /* use `public virtual Product` if lazy loading is needed */
}

Cascading

GroupDiscount ←→ GroupDiscountPerson

GroupDiscount entity model does not need a declaration. However, GroupDiscountPerson should have the following declaration in the model.

[Required] // *** Use [Required] with Caution - explained below *** public string GroupDiscountId { get; set; }

By doing this, GROUP_DISCOUNT_ID column is added to the GroupDiscountPerson table as a result.

Important Note: [Required] attribute applies “Cascade” deletion. Remove the required attribute if you want the deletion action changed to “No Action”. When No Action is selected as the deletion action, database prevents records from being deleted and throws an exception with status code 501.


Create 1 to 1 relationship w/ foreign key

// LookUp Table
public class LookUp : Entity<string> 
{
  [Key, Column(Order = 0), MaxLength(20)]
  public string Key { get; set; }

  [Key, Column(Order = 1), MaxLength(3)]
  [DatabaseGenerated(DatabaseGeneratedOption.None)]
  public override string Id { get; set; }
}

// InsuranceCompanyInfo Table
public class Info : Entity
{
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public override int Id { get; set; }
      
  public LookUp.LookUp LookUp { get; set; }

  [ForeignKey("LookUp"), Column(Order = 0)]
  [DefaultValue("InsuranceCompany"), MaxLength(20)]
  public string LookUpKey { get; set; }

  [ForeignKey("LookUp"), Column(Order = 1)]
  [MaxLength(3)]
  public string LookUpId { get; set; }
}

Create nullable columns

public DateTime? EndDateTime { get; set; }
public byte? IdentityType { get; set; }
public int? IdentityType { get; set; }
public string Name {get; set; }
public bool NotValidAbroad { get; set; }
public IdentityTypeEnum? DefaultIdentityType { get; set; }

https://www.devart.com/dotconnect/mysql/docs/DataTypeMapping.html

Use the TypeName parameter in the column attribute to change the appropriate data
type of the corresponding db column, as shown below.

public class Student
{
    [Column("DoB", TypeName="DateTime2")]
    public DateTime DateOfBirth { get; set; } // => datetime2(7) (mssql)
    public byte[] Photo { get; set; } // => varbianry (mssql)
    public decimal Height { get; set; } // => decimal (mssql)
    public float Weight { get; set; } // => real (mssql)
}
@* MAIN VIEW *@
@*-----------*@

@model GroupDiscountPersonViewModel
@{
  var modelType = typeof(GroupDiscountPersonViewModel);
  var modelData = ModelMetadataProviders.Current.GetMetadataForType(null, modelType);
}

@Html.Partial("_ModalFileUpload", modelData)


@* PARTIAL VIEW *@
@*--------------*@

@{
  var modelData = Model;/* passed the modeldata directly instead of the viewmodel. */
  foreach (var p in modelData.Properties)
  {
    if (p.PropertyName.Contains("ChkBox"))
    {
    
    }
  }
}
/****** MODEL **********/
[Display(Name = "Hastalık Detayı")]
[Required]
[AdditionalMetadata("ShowBlank", true)]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Bu alana sadece harf girebilirsiniz")]
[UIHint("LookUpsByKey")]
public string SicknessDetail { get; set; }

/****** EDITOR TEMPLATE - CSHTML **********/

@model dynamic
@{
  var modelData = ViewData.ModelMetadata;

  if (modelData.IsRequired)
  {
    var showBlank = modelData.AdditionalValues.FirstOrDefault(x => x.Key == "ShowBlank");
    var hasShowBlank = !showBlank.Equals(default(KeyValuePair<string, object>)) && (bool) showBlank.Value;
    @(hasShowBlank ? Html.DropDownList(fieldName, null, "", htmlAttributes) : Html.DropDownList(fieldName, null, htmlAttributes))
  }
  else
  {
    @Html.DropDownList(fieldName, null, "", htmlAttributes);
  }
}
/*
  when email class is serialized, property names are set as given
  by the JsonProperty data annotation.
  JsonIgnore annotation causes the prop to be serialized.
*/

namespace Health.Messaging
{
  [NotMapped]
  public class Email
  {
    [JsonIgnore]
    public int SirketKod { get; set; }

    [JsonProperty("EMAIL_PAZ_OPR")]
    public int EmailPazOpr { get; set; }

  }
}

Changes the PK field type to String

Id PK field is integer by default.

public class Product : Entity<string>
{
  [MaxLength(3)]
  public override string Id { get; set; }
}

Convert Model to Json

@model EndorsementViewModel

@Html.Script(
  @<script>
    window.insureds = @Html.Raw(Json.Encode(Model.Insureds));
  </script>
)

---

// For bigger datasets use this"

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model);

<script>
  $(function () {
    var viewModel = @Html.Raw(jsonModel);
  });
</script>

DisplayName

public string DisplayName => 
  ParentCoverageId != null 
      ? string.Concat(ParentCoverageId + " > " + Id, " - ", Name) 
      : string.Concat(Id, " - ", Name);

Enum Table Colyumn Data Type & Size

use inheritance in this case :byte is specified as the col data type and size. code below will create table column with data type; Number(3).

public enum ListConditionEnum : byte
{
  [Description("Yetkisi Yok")]
  Out = 0,
  [Description("Yetkisi Var")]
  In = 1
}