EF - One to one relationship RRS feed

  • Question

  • I have the following class:

    public class FinanceiroLancamento
        /// <summary>Identificação</summary>
        public override int Id { get; set; }
        /// <summary>Financeiro caixa</summary>
        public FinanceiroLancamentoCaixa FinanceiroLancamentoCaixa { get; set; }
    public class FinanceiroLancamentoCaixa
        /// <summary>Identificação</summary>
        public override int Id { get; set; }
        /// <summary>Identificação do lançamento financeiro</summary>        
        public int IdFinanceiroLancamento { get; set; }

    When I try to map and execute migration it´s return:

    Property name 'IdFinanceiroLancamento' was already defined.

    To solve this problem I needed to comment idfinanceirolancamento and map like this:

            HasRequired(e => e.FinanceiroLancamentoCaixa)
                .Map(m => m.MapKey("IdFinanceiroLancamento"));

    The question is: How can I this FK (FinanceiroLancamento -> FinanceiroLancamentoCaixa) keeping the "IdFinanceiroLancamento { get; set; }"?

    This is very important in my case to use later in the class.

    Ps: FinanceiroLancamento does not need a FinanceiroLancamentoCaixa, but when FinanceiroLancamentoCaixa exists he needs a FinanceiroLancamento.

    Best regards.

    Wilton Ruffato Wonrath

    Wilton R. Wonrath

    Friday, April 26, 2013 1:01 PM


  • Hi Wilton,

    MapKey method is used to configure the name of the foreign key columns in database. By convension, IdFinanceiroLancamento in FinanceiroLancamentoCaixa cannot be figured out as a foreign key by EF, and a foreign key named "IdFinanceiroLancamento" in the database because of the MapKey method. So there will be conflicts with the IdFinanceiroLancamento property.

    Unlike MapKey method, HasForeignKey method is used to configure which property represents the foreign key. However, the Code First does not natively support one-to-one relationship foreign key associations.

    If you need the IdFinanceiroLancamento property, you can try to also add a navigation property and then follow this article to create unique constraint by overriding Seed method in a custom initializer class:


    Best regards,

    Chester Hong
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Chester Hong Tuesday, May 7, 2013 9:21 AM
    Tuesday, April 30, 2013 6:37 AM