친애하는 동료 프로그래머,일대일 데이터베이스 우선 EF
내가 EF 내에서이 기본 개념에 붙어과 유래에 어떤 해결책을 찾을 수 없습니다.
FluxLocation과 Address 사이의 일대일 선택적 관계가 있어야합니다. (일반어 : 플럭스 위치에 실제 주소가 제공 될 수 있음)
데이터베이스가 이미 있으며 최종 버전입니다.
SQL의 테이블 :
CREATE TABLE sales.sales_flux_location(
id serial PRIMARY KEY,
-- Many unusefull properties
sales_address_id integer REFERENCES sales_address
);
CREATE TABLE sales.sales_address(
id serial PRIMARY KEY,
-- Many unusefull properties
);
EF 매핑 :
public partial class FluxLocation
{
public int Id { get; set; }
//Many unusefull properties.
[ForeignKey("Address")]
public int? AddressId { get; set; }
public Address Address { get; set; }
}
internal partial class FluxLocationConfiguration : EntityTypeConfiguration<FluxLocation>
{
public FluxLocationConfiguration()
{
//PK
HasKey(x => x.Id);
ToTable("sales_flux_location", "sales");
Property(a => a.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//FK
HasOptional(l => l.Address)
.WithOptionalDependent(a => a.FluxLocation);
Property(l => l.AddressId)
.HasColumnName("sales_address_id")
.IsOptional();
// + mapping other properties.
}
public partial class Address
{
public int Id { get; set; }
// other properties
public FluxLocation FluxLocation { get; set; }
}
internal partial class AddressConfiguration : EntityTypeConfiguration<Address>
{
public AddressConfiguration()
{
//PK
HasKey(a => a.Id);
ToTable("sales_address", "sales");
Property(a => a.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//FK
HasOptional(a => a.FluxLocation).WithOptionalPrincipal(l=>l.Address);
// mapping many unusefull properties
}
테스트 케이스 : Context.SaveChanges에
var dbAddress = Context.AddressSet.Add(new Address {Country = "BEL", CityName="Brussel", Street = Guid.NewGuid().ToString() });
var dbLocation = Context.FluxLocationSet.Add(new FluxLocation { AddressId = dbAddress.Id, Country = "BEL", Type = "MARKET", ExtId = Guid.NewGuid().ToString() });
Context.SaveChanges();
오류() :
열 이름이 "sales_address_id는"때문에 올바른 "관계 \의": "42703 열 \"Address_Id \ sales_flux_location의 \ "존재하지 않는"}
. 그가 propery columnname 매핑을 무시하는 이유를 도울 수 있다면? 필요한 경우 더 많은 코드를 제공하게되어 기쁩니다.
그것을 따기되지 않으며, 그 아무데도 구성되지 않았습니다! EF는 협약 당 PK = FK로 각 일대일 관계를 구현할 것이기 때문에 별의 차이는 0 : 1 관계뿐만 아니라 1 : 1에도 해당됩니다. 제안 된 솔루션은이 규칙을 우회하는 유일한 방법입니다. 다른 (WithRequired/WithOptional이 FK를 선언 할 수 없기 때문에 다른 것만 알고 있습니다) 방법은 Data Annotation ForeignKey를 사용하는 것입니다. 아무 비평가도,이 짧은 대답에 단지 설명/추가. – DevilSuichiro
더 자세한 솔루션을 제공해 주셔서 감사합니다.이 설정으로 EF를 속일 까봐 조금 까다 롭습니다. 스티브 그린 (Steve Greene)이 1 : m을 여전히 사용하도록 하겠지만 컬렉션에 매핑하고이를 무시하는 EF에 대한 다른 속성을 만들어 목록의 첫 번째 항목을 반환합니다. 코드에 제한이 있습니다. –