Using the Northwind database, I have generated all of the entities from that table using EF6.
Now I would like to create an additional custom entity, which is not an existing table, but it pulls data from three existing tables. The custom entity is "OrderCustomized".
public class OrderCustomized
{
public int OrderID { get; set; }
public DateTime? OrderDate { get; set; }
public string CustomerID { get; set; }
public string CustomerContactName { get; set; }
public string CustomerPhone { get; set; }
public int? EmployeeID { get; set; }
public string EmployeeLastName { get; set; }
public string EmployeeFirstName { get; set; }
}
public partial class NorthwindEntities : DbContext
{
public NorthwindEntities()
: base("name=NorthwindEntities")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//throw new UnintentionalCodeFirstException();
modelBuilder.Entity<OrderCustomized>()
.Map(m =>
{
m.Properties(o => new { o.OrderID, o.OrderDate, o.CustomerID, o.EmployeeID });
m.ToTable("Order");
})
.Map(m =>
{
m.Properties(c => new { c.CustomerID, c.CustomerContactName, c.CustomerPhone });
m.ToTable("Customer");
})
.Map(m =>
{
m.Properties(e => new { e.EmployeeID, e.EmployeeLastName, e.EmployeeFirstName });
m.ToTable("Employee");
})
;
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Contact> Contacts { get; set; }
public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Order_Detail> Order_Details { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Shipper> Shippers { get; set; }
public virtual DbSet<Supplier> Suppliers { get; set; }
public virtual DbSet<Territory> Territories { get; set; }
public virtual DbSet<OrderCustomized> OrdersCustomized { get; set; }
}
I keep getting the error "The entity type OrderCustomized is not part of the model for the current context."
How do I made OrderCustomized part of the model for the current context?
I would really appreciate any sample code, as I cannot find any when searching the internet.
Thanks,
Kellie
Remember to update T4 file (.tt extension). Let me know does it work after that operation.
Related
I am trying to create a Product table that will have a list of SubstitutionProducts that should reference other Product from the same table.
Model example :
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsMissing { get; set; }
public ICollection<Product> SubstitutionProducts { get; set; }
}
It is better to include the parent ID in your model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsMissing { get; set; }
public int? ParentId { get; set; }
public Product Parent { get; set; }
public ICollection<Product> SubStitutionProducts { get; set; }
}
This is how to configure DB schema via overriding OnModelCreatingmethod of your DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasOne(x => x.Parent)
.WithMany(x => x.SubStitutionProducts)
.HasForeignKey(x => x.ParentId).IsRequired(false);
}
I am trying to pass a raw sql join with entity framework on my web api. this is my api code.
namespace HannaOilAndGas2.Controllers
{
[Produces("application/json")]
[Route("api/mainview")]
public class MainViewApi : Controller
{
private readonly ScadaContext _context;
public MainViewApi(ScadaContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
[Route("allmainview")]
public IEnumerable<Device> GetAllMainView()
{
return _context.Device.FromSql(
"SELECT PD.RecId, D.Location, Round(PD.SPOT_FLOW_RATE,0), Round(PD.PREVIOUS_DAY_VOLUME,0)," +
"Round(PD.LINE_PRESSURE,0), Round(PD.DIFFERENTIAL_PRESSURE,0), Round(PD.TEMPERATURE,0)," +
"Round(PD.BATTERY_VOLTAGE,0) ROUND(PD.FCP,0), ROUND(PD.FTP,0) D.LAST_COMMUNICATION, D.LAST_COMMUNICATION_METHOD" +
"FROM DEVICE D" +
"JOIN POLL_DATA PD" +
"ON D.HANNA_DEVICE_ID = PD.HANNA_DEVICE_ID").Where(x => x.MeterId != "HOGC%");
}
my device model looks like this because all of these tables relate to device
namespace HannaOilAndGas2.Data
{
public partial class Device
{
public Device()
{
DailyData = new HashSet<DailyData>();
PollBattery = new HashSet<PollBattery>();
PollDifferentialPressure = new HashSet<PollDifferentialPressure>();
PollFcp = new HashSet<PollFcp>();
PollFtp = new HashSet<PollFtp>();
PollLinePressure = new HashSet<PollLinePressure>();
PollPdVolume = new HashSet<PollPdVolume>();
PollSpotFlowRate = new HashSet<PollSpotFlowRate>();
PollTemperature = new HashSet<PollTemperature>();
PollData = new HashSet<PollData>();
ChokeHistory = new HashSet<ChokeHistory>();
CommentsHistory = new HashSet<CommentsHistory>();
ContractHourHistory = new HashSet<ContractHourHistory>();
HourlyData = new HashSet<HourlyData>();
MeterTubeSizeHistory = new HashSet<MeterTubeSizeHistory>();
OrificeCoeffHistory = new HashSet<OrificeCoeffHistory>();
PlateSizeHistory = new HashSet<PlateSizeHistory>();
PollDataHistorical = new HashSet<PollDataHistorical>();
ShutinHistory = new HashSet<ShutinHistory>();
}
public int HannaDeviceId { get; set; }
public int? MdbDeviceId { get; set; }
public string SpreadsheetId { get; set; }
public string SpectraId { get; set; }
public string ServiceStarId { get; set; }
public string MeterId { get; set; }
public string Location { get; set; }
public float? ShutinPressure { get; set; }
public float? Latitude { get; set; }
public float? Longitude { get; set; }
public float? Choke { get; set; }
public float? OrificeCoeff { get; set; }
public decimal? MeterTubeSize { get; set; }
public float? ContractHour { get; set; }
public string SecTwnRange { get; set; }
public string County { get; set; }
public string State { get; set; }
public decimal? PlateSize { get; set; }
public string Comments { get; set; }
public DateTime? LastCommunication { get; set; }
public string LastCommunicationMethod { get; set; }
public virtual ICollection<DailyData> DailyData { get; set; }
public virtual ICollection<PollBattery> PollBattery { get; set; }
public virtual ICollection<PollDifferentialPressure> PollDifferentialPressure { get; set; }
public virtual ICollection<PollFcp> PollFcp { get; set; }
public virtual ICollection<PollFtp> PollFtp { get; set; }
public virtual ICollection<PollLinePressure> PollLinePressure { get; set; }
public virtual ICollection<PollPdVolume> PollPdVolume { get; set; }
public virtual ICollection<PollSpotFlowRate> PollSpotFlowRate { get; set; }
public virtual ICollection<PollTemperature> PollTemperature { get; set; }
public virtual ICollection<PollData> PollData { get; set; }
public virtual ICollection<ChokeHistory> ChokeHistory { get; set; }
public virtual ICollection<CommentsHistory> CommentsHistory { get; set; }
public virtual ICollection<ContractHourHistory> ContractHourHistory { get; set; }
public virtual ICollection<HourlyData> HourlyData { get; set; }
public virtual ICollection<MeterTubeSizeHistory> MeterTubeSizeHistory { get; set; }
public virtual ICollection<OrificeCoeffHistory> OrificeCoeffHistory { get; set; }
public virtual ICollection<PlateSizeHistory> PlateSizeHistory { get; set; }
public virtual ICollection<PollDataHistorical> PollDataHistorical { get; set; }
public virtual ICollection<ShutinHistory> ShutinHistory { get; set; }
}
}
this is my context
public partial class ScadaContext : DbContext
{
public ScadaContext(DbContextOptions<ScadaContext> options) : base(options)
{}
public ScadaContext()
{
}
public virtual DbSet<ChokeHistory> ChokeHistory { get; set; }
public virtual DbSet<CommentsHistory> CommentsHistory { get; set; }
public virtual DbSet<ContractHourHistory> ContractHourHistory { get; set; }
public virtual DbSet<DailyData> DailyData { get; set; }
public virtual DbSet<Device> Device { get; set; }
public virtual DbSet<HourlyData> HourlyData { get; set; }
public virtual DbSet<MeterTubeSizeHistory> MeterTubeSizeHistory { get; set; }
public virtual DbSet<OrificeCoeffHistory> OrificeCoeffHistory { get; set; }
public virtual DbSet<PlateSizeHistory> PlateSizeHistory { get; set; }
public virtual DbSet<PollBattery> PollBattery { get; set; }
public virtual DbSet<PollData> PollData { get; set; }
public virtual DbSet<PollDataHistorical> PollDataHistorical { get; set; }
public virtual DbSet<PollDifferentialPressure> PollDifferentialPressure { get; set; }
public virtual DbSet<PollFcp> PollFcp { get; set; }
public virtual DbSet<PollFtp> PollFtp { get; set; }
public virtual DbSet<PollLinePressure> PollLinePressure { get; set; }
public virtual DbSet<PollPdVolume> PollPdVolume { get; set; }
public virtual DbSet<PollSpotFlowRate> PollSpotFlowRate { get; set; }
public virtual DbSet<PollTemperature> PollTemperature { get; set; }
public virtual DbSet<ShutinHistory> ShutinHistory { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ChokeHistory>(entity =>
{
entity.HasKey(e => e.RecId)
.HasName("PK_CHOKE_HISTORY");
entity.ToTable("CHOKE_HISTORY");
entity.Property(e => e.RecId).HasColumnName("RecID");
entity.Property(e => e.Choke).HasColumnName("CHOKE");
entity.Property(e => e.HannaDeviceId).HasColumnName("HANNA_DEVICE_ID");
entity.Property(e => e.ImportMethod)
.IsRequired()
.HasColumnName("IMPORT_METHOD")
.HasMaxLength(50);
entity.Property(e => e.Timestamp)
.HasColumnName("TIMESTAMP")
.HasColumnType("datetime")
.HasDefaultValueSql("getdate()");
entity.HasOne(d => d.HannaDevice)
.WithMany(p => p.ChokeHistory)
.HasForeignKey(d => d.HannaDeviceId)
.HasConstraintName("FK_CHOKE_HISTORY_DEVICE");
});
all my tables are set up following this I would like to get the query in the api to work but all I get back is an empty result of []. I am fairly new to entity framework I have read that you could do raw sql like that. I am not sure what I am doing wrong any help would be appreciated. My app is a .net core 1.1 application.
There are a couple of limitations to be aware of when using raw SQL queries:
SQL queries can only be used to return entity types that are part of
your model. There is an enhancement on our backlog to enable
returning ad-hoc types from raw SQL queries.
The SQL query must return data for all properties of the entity type.
The column names in the result set must match the column names that
properties are mapped to. Note this is different from EF6.x where
property/column mapping was ignored for raw SQL queries and result
set column names had to match the property names.
The SQL query cannot contain related data. However, in many cases you
can compose on top of the query using the Include operator to return
related data (see Including related data).
https://learn.microsoft.com/en-us/ef/core/querying/raw-sql
You can use Dapper liberary for raw sql or use Linq query.
Just replace your where clause here:
Where(x => x.MeterId != "HOGC%")
...to be like this:
Where(x => !x.MeterId.Startswith("HOGC"))
This will act like the NOT LIKE in SQL (due to the ! operator).
I’m pretty new to EF and I have a little problem.
I just want to delete an item in my database. I’m using SQL Server 2012 Express, VS2012, AdventureWorks 2012.
The query that I execute is the following:
context = new AWEntities();
var removedItem = context.Addresses
.Include("StateProvince")
.Include("SalesOrderHeaders")
.Include("BusinessEntityAddresses").Single(d => d.AddressID == 11);
context.Addresses.Remove(removedItem);
context.SaveChanges();
The error that I get is
The DELETE statement conflicted with the REFERENCE constraint "FK_SalesOrderHeader_Address_ShipToAddressID". The conflict occurred in database "AdventureWorks2012", table "Sales.SalesOrderHeader", column 'ShipToAddressID'.
The statement has been terminated.
Is this actually a good way to delete items and the according entries in the other tables?
Please point me into the right direction.
public partial class Address
{
public Address()
{
this.BusinessEntityAddresses = new HashSet<BusinessEntityAddress>();
this.SalesOrderHeaders = new HashSet<SalesOrderHeader>();
}
public int AddressID { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public int StateProvinceID { get; set; }
public string PostalCode { get; set; }
public System.Data.Spatial.DbGeography SpatialLocation { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual StateProvince StateProvince { get; set; }
public virtual ICollection<BusinessEntityAddress> BusinessEntityAddresses { get; set; }
public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
}
public partial class StateProvince
{
public StateProvince()
{
this.Addresses = new HashSet<Address>();
this.SalesTaxRates = new HashSet<SalesTaxRate>();
}
public int StateProvinceID { get; set; }
public string StateProvinceCode { get; set; }
public string CountryRegionCode { get; set; }
public bool IsOnlyStateProvinceFlag { get; set; }
public string Name { get; set; }
public int TerritoryID { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual CountryRegion CountryRegion { get; set; }
public virtual ICollection<SalesTaxRate> SalesTaxRates { get; set; }
public virtual SalesTerritory SalesTerritory { get; set; }
}
}
public partial class BusinessEntityAddress
{
public int BusinessEntityID { get; set; }
public int AddressID { get; set; }
public int AddressTypeID { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Address Address { get; set; }
public virtual AddressType AddressType { get; set; }
public virtual BusinessEntity BusinessEntity { get; set; }
}
public partial class SalesOrderHeader
{
public SalesOrderHeader()
{
this.SalesOrderDetails = new HashSet<SalesOrderDetail>();
this.SalesOrderHeaderSalesReasons = new HashSet<SalesOrderHeaderSalesReason>();
}
public int SalesOrderID { get; set; }
public byte RevisionNumber { get; set; }
public System.DateTime OrderDate { get; set; }
public System.DateTime DueDate { get; set; }
public Nullable<System.DateTime> ShipDate { get; set; }
public byte Status { get; set; }
public bool OnlineOrderFlag { get; set; }
public string SalesOrderNumber { get; set; }
public string PurchaseOrderNumber { get; set; }
public string AccountNumber { get; set; }
public int CustomerID { get; set; }
public Nullable<int> SalesPersonID { get; set; }
public Nullable<int> TerritoryID { get; set; }
public int BillToAddressID { get; set; }
public int ShipToAddressID { get; set; }
public int ShipMethodID { get; set; }
public Nullable<int> CreditCardID { get; set; }
public string CreditCardApprovalCode { get; set; }
public Nullable<int> CurrencyRateID { get; set; }
public decimal SubTotal { get; set; }
public decimal TaxAmt { get; set; }
public decimal Freight { get; set; }
public decimal TotalDue { get; set; }
public string Comment { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Address Address { get; set; }
public virtual ShipMethod ShipMethod { get; set; }
public virtual CreditCard CreditCard { get; set; }
public virtual CurrencyRate CurrencyRate { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<SalesOrderDetail> SalesOrderDetails { get; set; }
public virtual SalesPerson SalesPerson { get; set; }
public virtual SalesTerritory SalesTerritory { get; set; }
public virtual ICollection<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }
}
Can't really tell much from what you have said, but you may benefit from looking into using the DbModelBuilder to solve cascade issues:
modelBuilder.Entity<Parent>()
.HasMany<Child>(c => c.Children)
.WithOptional(x => x.Parent)
.WillCascadeOnDelete(true);
Again, would need more information about your model structure to determine if this is the right approach.
Either that or in your delete method, remove any children first, and then remove the parent.
modelBuilder.Entity<Parent>()
.HasMany<Child>(c => c.Children)
.WithOptional(x => x.Parent)
.WillCascadeOnDelete(true);
or use Include
var adv = db.Adv.Include(b => b.Features)
.Include(b => b.AdvDetails)
.Include(b => b.AdvGallery)
.FirstOrDefault(b => b.Id == id);
db.Adv.Remove(adv);
for .HasMany(...).WithMany(...) Include is ok
You can resolve this issue on SQL side
Method 1 :
First, you need to find on which table this FK constraint has been defined, through using Replication monitor.
Right click on that FK, click Modify, you should get popup box like one shown below.
From the popup box, Select Cascade for del.
Method 2 :
set ON DELETE CASCADE in sql at the end of constraint.
In EF Core the syntax in builder is as follows:
builder.HasOne(b => b.Parent )
.WithMany(a => a.Children)
.OnDelete(DeleteBehavior.Cascade);
https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete
I got this error when I created Entity B, that referenced Entity A, and then tried to delete Entity A. SQL/EF did not allow me to leave that dangling Id reference, since the objcet no longer existed. Cascading deletes would solve this, but I wanted B to persist. So I have to remove the reference from B before deleting A:
var existingContractApprovers = _repo.Query<ChangeOrderApproverForContract>().Where(coafc => coafc.ContractId == key).ToList();
//remove refs to contract approvers to preserve data integrity
foreach(var contractApp in existingContractApprovers)
{
var associatedChangeOrderApprovers = _repo.Query<ChangeOrderApprover>().AsNoTracking().Where(coafc => coafc.ChangeOrderApproverForContractId == contractApp.Id).ToList();
foreach(var coApp in associatedChangeOrderApprovers)
{
_repo.Edit(coApp);
coApp.ChangeOrderApproverForContractId = null;
}
}
_repo.SaveChanges();
//remove the contract approvers
foreach (var contractApp in existingContractApprovers)
{
_repo.Delete(contractApp);
}
_repo.SaveChanges();
You can do this in EF Core.
modelBuilder.Entity<Parent>()
.HasMany<Child>(c => c.Children)
.WithOne(s => s.Parent)
.OnDelete(DeleteBehavior.Cascade);
The safer alternative is to make sure all children are deleted before deleting the parent. You should cascade on delete only if you are completely aware of how your entities relate. For example, you could have lots of orders connected to
a certain category in your e-commerce store. Once the category is deleted, all the orders and any entity whose foreign keys are connected to this parent category will be gone.
I have two entities, a User and a UserProfile. The PK of User is UserId, the PK of UserProfile is UserProfileId. Every time a new user is created in my app, I create a new UserProfile whose PK is the same as the PK in User. When I then try to go update properties on the UserProfile I end up getting multiplicity errors or schema invalid errors. Here are my two entities:
public class User
{
public Guid UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? PhoneExtension { get; set; }
public string Comment { get; set; }
public Boolean IsApproved { get; set; }
public int PasswordFailuresSinceLastSuccess { get; set; }
public DateTime? LastPasswordFailureDate { get; set; }
public DateTime? LastActivityDate { get; set; }
public DateTime? LastLockoutDate { get; set; }
public DateTime? LastLoginDate { get; set; }
public string ConfirmationToken { get; set; }
public DateTime? CreateDate { get; set; }
public Boolean IsLockedOut { get; set; }
public DateTime? LastPasswordChangedDate { get; set; }
public string PasswordVerificationToken { get; set; }
public DateTime? PasswordVerificationTokenExpirationDate { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
public class UserProfile
{
public Guid UserProfileId { get; set; }
public virtual User ProfileOwner { get; set; }
public Int64? HomePhone { get; set; }
public Int64? MobilePhone { get; set; }
public virtual User Manager { get; set; }
}
..and here are my only defined relationships using Fluent API.
modelBuilder.Entity<UserProfile>()
.HasKey(e => e.UserProfileId);
modelBuilder.Entity<UserProfile>()
.Property(e => e.UserProfileId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<UserProfile>()
.HasRequired(e => e.ProfileOwner)
.WithRequiredDependent(r => r.UserProfile);
Finally, my UserService creates a new user and at the same time creates a new UserProfile whose Guid UserProfileId is the same as the User's Guid UserId. Right after the user and profile are created, I try to update the manager in the UserProfile with my UserProfileService using this:
public void UpdateUserProfile(UserProfile updatedUserProfile)
{
UserProfile oldUserProfile = GetUserProfileByID(updatedUserProfile.UserProfileId);
oldUserProfile.Manager = updatedUserProfile.Manager;
oldUserProfile.HomePhone = updatedUserProfile.HomePhone;
oldUserProfile.MobilePhone = updatedUserProfile.MobilePhone;
this.SetEntityState(oldUserProfile, EntityState.Modified);
this.UnitOfWork.SaveChanges();
}
The this.SetEntityState line throws this error:
Multiplicity constraint violated. The role 'UserProfile_ProfileOwner_Source' of the relationship 'WhelenPortal.Data.Context.UserProfile_ProfileOwner' has multiplicity 1 or 0..1.
I've been trying to get this working for TWO DAYS now, PLEASE HELP!!! Thanks in advance.
As requested, here is some additional information. I'm using the repository pattern and unit of work here. My GetUserProfileById code is below. The service uses the repository so I show both.
public UserProfile GetUserProfileByID(Guid id)
{
if (id == null)
throw new BusinessServicesException(Resources.UnableToRetrieveUserProfileExceptionMessage, new ArgumentNullException("id"));
try
{
Model.UserProfile userProfile = _userProfileRepository.GetUserProfileByID(id);
if (userProfile != null)
return ToServicesUserProfile(userProfile);
return null;
}
catch (InvalidOperationException ex)
{
throw new BusinessServicesException(Resources.UnableToRetrieveUserProfileExceptionMessage, ex);
}
}
..and the repository:
public UserProfile GetUserProfileByID(Guid id)
{
return this.GetDbSet<UserProfile>().Find(id);
}
So after much playing around this is what ended up working for me, hopefully it can help someone else in some fashion. My User class stayed exactly the same but my UserProfile class changed to this:
public class UserProfile
{
public Guid UserProfileId { get; set; }
public virtual User ProfileOwner { get; set; }
public Guid? ManagerId { get; set; }
public virtual User Manager { get; set; }
public Int64? HomePhone { get; set; }
public Int64? MobilePhone { get; set; }
}
And here is the fluent mapping:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasOptional(u => u.UserProfile)
.WithRequired(u => u.ProfileOwner);
modelBuilder.Entity<UserProfile>()
.HasOptional(u => u.Manager)
.WithMany()
.HasForeignKey(u => u.ManagerId);
}
I have a composite table called ImporterState, that are tied to a table called Importer and State. The error happens here context.Importers.Include(q => q.States). Why is this happening?
{"Invalid object name 'ImporterStates'."}
[Table("HeadlineWebsiteImport", Schema = "GrassrootsHoops")]
public class Importer
{
public int Id { get; set; }
public string Name { get; set; }
public string RssUrl { get; set; }
public string Type { get; set; }
public string Keywords { get; set; }
public bool Active { get; set; }
public DateTime DateModified { get; set; }
public DateTime DateCreated { get; set; }
public int WebsiteId { get; set; }
public HeadlineWebsite Website { get; set; }
[InverseProperty("Importers")]
public ICollection<State> States { get; set; }
}
[Table("State", Schema = "GrassrootsHoops")]
public class State
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Abbr { get; set; }
[InverseProperty("States")]
public ICollection<Headline> Headlines { get; set; }
[InverseProperty("States")]
public ICollection<Importer> Importers { get; set; }
}
The many to many is not possible using attributes only.
try using something like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Importer>()
.HasMany(i => i.States)
.WithMany(s => s.Importers)
.Map(m =>
{
m.MapLeftKey("ImporterId");
m.MapRightKey("StateId");
m.ToTable("ImporterState");
});
}