Invalid line length in Entity framework

I am using EF6 (Code First) in a project.

Having a class below:

public class State
{
    public int ID { get; set; }

    [Required]
    [StringLength(10)]
    public string Code { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [Required]
    public Country Country { get; set; }
}

I expect to have Codeboth nvarchar(10)in the database, but I get nvarchar(3). I see the correct length for the column Name, but I can not understand why it was Codecreated incorrectly.

Edit: I have a Country class as shown below:

public class Country
{
    [Key]
    [StringLength(3)]
    public string Code { get; set; }


    [Required]
    [StringLength(50)]
    public string Name { get; set; }
}

I think EF believes that the Code in State class is a Code in Country class, as there is an association between them.

Now the question is, how should I tell EF that the Code in State class is not a Foreign Key to Country class?

+4
source share
3 answers

EF . , EF {Navigation Property Name}{Referenced Entity PK Property Name} FK . (), , {Referenced Entity PK Property Name}.

ForeignKey ( FK/navigation), , , , MapKey , :

modelBuilder.Entity<State>()
    .HasRequired(s => s.Country)
    .WithMany(s => s.States)
    .Map(s => s.MapKey("CountryCode"));
+2

MaxLength , EF , .

StringLength - , .

MSDN:

MaxLength. , .

StringLength. , .

:

[ForeignKey("CountryCode")], Code Country CountryCode ( ) Column["Code"]:

public class State
{
    public int ID { get; set; }

    [Required]
    [StringLength(10)]
    public string Code { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [Required]
    [ForeignKey("CountryCode")]
    public Country Country { get; set; }
}

public class Country
{
    [Key]
    [StringLength(3)]
    [Column["Code"]]
    public string CountryCode { get; set; }


    [Required]
    [StringLength(50)]
    public string Name { get; set; }
}

MSDN: , ForeignKey

Code StateCode CountryCode [ForeignKey("CountryCode")].

+3

State model, , , , , EF , :

public string CountryId { get; set; } 

if you want to choose a different name than CountryId, suppose you want to change it to CountryForeignKey, you can use the following:

 using System.ComponentModel.DataAnnotations.Schema;
.
.
.
[ForeignKey("CountryForeignKey")]
        public Country Country { get; set; }

        public string CountryForeignKey { get; set; } 

and this is what you get in the database enter image description here

+2
source

Source: https://habr.com/ru/post/1688500/


All Articles