简体   繁体   中英

Entity Framework 6 - 0..1 RelationShip Mapping

I have two classes:

public class Report
{
    public int IdReport {get;set;}

    public int IdModel {get;set;}

    public Model MyModel {get;set;}
}

public class Model
{
    public int IdModel {get;set;}

    public Report MyReport {get;set}
}

I have this configuration class:

public class ReportConfiguration : EntityTypeConfiguration<Report>
{
     HasOptional(c => c.Model).WithOptionalPrincipal(d => d.Report)....
}

This is where I got stuck, how can get the HasForeignKey(c => c.IdModel) configuration

I need this because we have a form using binding source, and a report can have or not a model(since we make dynamic reports).

I dont wanna create a fake foreign key, like creating a property and on report insert, I set this property value with primary key from the model. This is a way I found to fill the bindingsource with correctly value to be bounded with the combobox value edit.

I see that the navigation propertu MyModel.IdModel can provide this funcionality, but does binding source can accomplish this approach ?

I'm not sure that this is exactly what you need but this will create a nullable foreign key relationship from Report to Model and vice versa:

public class Report
{
    public int ReportId { get; set; }

    public int? ModelId { get; set; }

    public Model Model { get; set; }
}

public class Model
{
    public int ModelId {get; set;}

    public Report Report { get; set; }

    public int ReportId { get; set; }
}

public class ReportConfiguration : EntityTypeConfiguration<Report>
{
    public ReportConfiguration()
    {
        this.ToTable("Report");

        this.HasOptional(m => m.Model).WithMany().HasForeignKey(m => m.ModelId).WillCascadeOnDelete(false);
    }
}

Hope it helps.

With your mapping, Report is the principal entity, which means that Model has the foreign key. So you wouldn't be able to set a ModelId in Report anyway. You have to set the Model in stead.

Technically, this is not a big deal. You can populate a combobox (or a bindingsource) with Models , not set a ValueMember and bind the SelectedItem .

Performance-wise it probably doesn't really matter either, unless Model has very wide records and you intended to only select its Id and Name properties. Now you have to fetch the full objects from the database.

I've always wondered why the 1-1 API doesn't allow defining a foreign key association (ie a reference and primitive foreign key pair) but forces you to work with an independent association (reference only). So far, the reason is not clear to me. It looks to me that, in this case, Model could have had a ReportId exposed in the class model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM