我的数据库有一个来自第三方公司的约定,即“数据库中的所有列都必须是'not null'”。
现在我正在使用 EFCodefirst 映射所有表,但遇到了问题。
例如,我有一个与实体SA1
具有一对一关系的SA3
实体,我想添加一个新SA1
的,其a1_vend
属性为空字符串。
我为解决这个问题所做的就是SA3
在 PK 中添加一个带有空字符串的实体,但我不喜欢这种方法。我想要一个更好的解决方案来解决我的问题。
我的 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();
}
}