0
我的數據庫有一個來自第三方公司的約定,即「數據庫中的所有列必須爲'非空'」。EF CodeFirst - 與非空列對應的一對一關係 - 專家
現在我使用EFCodefirst映射所有表,並且遇到了一個問題。
例如,我有有一到一個關係到SA3
實體的實體SA1
,我想補充一個新的SA1
具有一個空字符串的a1_vend
財產。
我做了什麼來解決這個問題是在PK中添加一個SA3
實體的空字符串,但我不喜歡這種方法。我想更好地解決我的問題。
我EFCodefirst類:
[ComplexType]
public class Endereco
{
public string Logradouro { get; set; }
public string Numero { get; set; }
public string CEP { get; set; }
}
public class SA3
{
public string Codigo { get; set; }
public string Nome { get; set; }
}
public class SA1
{
public string Codigo { get; set; }
public string Nome { get; set; }
public Endereco Endereco { get; set; }
public Endereco EnderecoCobranca { get; set; }
public bool IsDeleted { get { return false; } }
public string a1_vend { get; set; }
public SA3 Vendedor { get; set; }
public SA1()
{
Endereco = new Endereco();
EnderecoCobranca = new Endereco();
}
}
public class SA3Map : EntityTypeConfiguration<SA3>
{
public SA3Map()
{
ToTable("sa3010");
HasKey(x => x.Codigo);
Property(x => x.Codigo)
.HasColumnName("a3_cod");
Property(x => x.Nome)
.HasColumnName("a3_nome");
}
}
public class SA1Map : EntityTypeConfiguration<SA1>
{
public SA1Map()
{
ToTable("sa1010");
HasKey(x => x.Codigo);
Property(x => x.Codigo)
.HasColumnName("a1_cod")
.IsRequired();
Property(x => x.Nome)
.HasColumnName("a1_nome")
.IsRequired();
Property(x => x.Endereco.Logradouro)
.HasColumnName("a1_end")
.IsRequired();
Property(x => x.Endereco.Numero)
.HasColumnName("a1_num")
.IsRequired();
Property(x => x.Endereco.CEP)
.HasColumnName("a1_cep")
.IsRequired();
Property(x => x.EnderecoCobranca.Logradouro)
.HasColumnName("a1_endcob")
.IsRequired();
Property(x => x.EnderecoCobranca.CEP)
.HasColumnName("a1_cepcob")
.IsRequired();
Property(x => x.EnderecoCobranca.Numero)
.HasColumnName("a1_numcob")
.IsRequired();
Property(x => x.a1_vend)
.IsRequired();
HasRequired(x => x.Vendedor)
.WithMany()
.HasForeignKey(x => new { x.a1_vend })
.WillCascadeOnDelete(false);
}
}
我的示例程序:
class Program
{
static void Main(string[] args)
{
MyContext ctx = new MyContext();
var novoVendedor = new SA3()
{
Codigo = "",
Nome = "Empty, don´t remove this row"
};
ctx.Vendedores.Add(novoVendedor);
var novoCliente = new SA1()
{
Codigo = "000001",
a1_vend = "", //I can´t use null here because my database convention
Endereco = new Endereco() { Numero = "99", CEP = "13280000", Logradouro = "Rua Teste" },
Nome = "Cliente S/A",
EnderecoCobranca = new Endereco { CEP = "13444999", Numero = "S/N", Logradouro = "Rua Cobranca" }
};
ctx.Clientes.Add(novoCliente);
ctx.SaveChanges();
}
}
我TREID做你說什麼,但它不T顯示我的選項MapLeftKey和MapRightKey,那隻能說明我映射鍵和ToTable。 HasRequired(X => x.Vendedor) .WithMany() .MAP(M => { m.ToTable( 「sa1_sa3_map」); //這裏doesn't顯示 } ); – will