Reputation: 101166
I'm trying to create EF CodeFirst mappings for a legacy database.
Lets say that I got the following classes:
public class Subscriber
{
public Guid Id { get; set; }
public SubscriberAddress Address { get; set; }
}
public class SubscriberAddress
{
//[...]
}
I want to configure a mapping between them. The tables looks like:
create table Subscriber
(
Id uniqueidentifier primary key,
-- [...]
)
create table SubscriberAddress
(
SubscriberId uniqueidentifier,
-- [...]
)
So the relation is in the SubscriberAddress
table, but in the classes I would like the address to be a property in the Subscriber
class.
I've tried with WithRequiredPrincipal
and WithRequiredDependent
but can't understand how to do the mapping since the FK is in the other table.
Edit
The SubscriberAddress
do not have a property referencing Subscriber
and Subscriber.Address
is optional.
Upvotes: 0
Views: 164
Reputation: 1217
Assuming that its a 1 to 1 relationship and both are required this should work.
public class SubscriberContext : DbContext
{
public DbSet<Subscriber> Subscribers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Entity<Subscriber>().HasRequired(x => x.Address).WithRequiredPrincipal(x => x.Subscriber);
modelBuilder.Entity<Subscriber>().HasOptional(x => x.Address).WithRequired(x => x.Subscriber);
modelBuilder.Entity<SubscriberAddress>().Property(x => x.Id).HasColumnName("SubscriberId");
base.OnModelCreating(modelBuilder);
}
}
public class Subscriber
{
public Guid Id { get; set; }
public virtual SubscriberAddress Address { get; set; }
}
public class SubscriberAddress
{
public Guid Id { get; set; }
public virtual Subscriber Subscriber { get; set; }
}
Upvotes: 1