Reputation: 91
I can't map the follow Database structure:
https://i.sstatic.net/iJmIq.png
I want a Logo (LogoID is a UniqueKey) for one Media. Follow my fluent mapping:
public class SponsorMap : EntityTypeConfiguration<Sponsor>
{
public SponsorMap()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
this.Property(t => t.Name)
.IsRequired()
.HasMaxLength(255);
this.Property(t => t.Description)
.IsRequired();
this.Property(t => t.SiteAddress)
.HasMaxLength(300);
this.Property(t => t.TwitterName)
.HasMaxLength(20);
this.Property(t => t.FacebookAddress)
.HasMaxLength(300);
// Relationships
//this.HasOptional(t => t.Logo);
this.HasOptional(t => t.Logo)
.WithOptionalDependent();
}
}
Follow Models:
public class Sponsor{
public Sponsor(){this.Goods = new List<Goods>();} public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string SiteAddress { get; set; }
public string TwitterName { get; set; }
public string FacebookAddress { get; set; }
public virtual ICollection<Goods> Goods { get; set; }
public virtual Media Logo { get; set; }
}
public class Media{
public Media(){}
public int ID { get; set; }
public string Path { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public virtual Goods Good { get; set; }
public virtual MediaType MediaType { get; set; }
}
I get follow error in my test:
Test method
Inove.Kenquer.Data.Tests.UserRepositoryTest.When_Save_User_With_Action_Get_Same_Actions_From_DB threw exception:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: **Invalid column name 'Logo_ID'.**
-----------------------------------------
MediaMap has no mapping to Sponsor.
How can I map it?
Upvotes: 0
Views: 1387
Reputation: 32447
You can map it like this.
public SponsorMap()
{
//other mappings
HasOptional(sponsor => sponsor.Logo)
.WithMany()
.Map(sponsor => sponsor.MapKey("LogoID"));
HasMany(sponsor => sponsor.Goods)
.WithOptional(good => good.Sponsor)
.Map(x => x.MapKey("SponsorID"));
}
Edit:
You need to map all navigational properties. I have added mapping between Sponsor
and Good
based on info you provided.
Go through some articles(eg : ADO.NET team blog) on how to use fluent mappings.
You can use EF power tools to generate mapping for you.
Upvotes: 2