实体框架代码中的可选1:1关系

时间:2015-04-30 15:10:12

标签: c# .net entity-framework

我试图在Entity Framework中创建我认为可选的1:1或可能0..1:0..1关系。我希望能够在两个对象上都有导航属性。

我在现有数据库架构上使用Entity Framework的Fluent API。

为简单起见,我们假设以下表格:

Car
    Id int not null

Driver
    Id int not null
    CarId int null unique

使用以下类:

public class Car
{
    public int Id { get; set; }
    public virtual Driver { get; set; }
}

public class Driver
{
    public int Id { get; set; }
    public virtual Car { get; set; }
}

这个想法是汽车和驾驶员可以彼此独立存在,但是当驾驶员与汽车相关联时,它是一个互斥的关联:驾驶员只能与该汽车相关联且该汽车只能关联那个司机。

我尝试了以下流畅的配置:

内部驱动程序的配置:

HasOptional(d => d.Car)
    .WithOptionalDependent()
    .Map(d => d.MapKey("CarId"));

在汽车配置中

HasOptional(c => cDriver)
    .WithOptionalPrincipal()
    .Map(d => d.MapKey("CarId"));

当我尝试这个时,我得到以下内容:

  

指定的架构无效。错误:   (203,6):错误0019:类型中的每个属性名称必须是唯一的。物业名称' CarId'已经定义了。

有没有办法使用Entity Framework中两个对象的导航属性为此场景建模?

2 个答案:

答案 0 :(得分:0)

您可以在没有Fluent API的情况下执行此操作:

CEQ_DA = @(w) fzero(@(CEQ) fp(CEQ, w),CEQ_DA_0);

然后你需要检查司机是否已经有车,以保证他只能有一辆车。

答案 1 :(得分:0)

您不需要在两个流利的课程中进行设置。我很惊讶这是你收到的错误,而不是已经建立了这种关系。

您的云端硬盘类需要CarId作为课程的一部分:

public class DialogLoginWelcome extends Dialog implements OnClickListener, IUserLoginListener, TimelineListener{

    TextView join, forgot;
    EditText email, password;
    Button login;
    LoginButton facebook;

    Boolean state;
    String fbEmail, fbPass;

    Calendar cal;
    Session session;
    IUserLoginListener mIUserLoginListener;
    UserLoginHelper mUserLoginHelper;

    Context context;


    public DialogLoginWelcome(Context context) {
        super(context);
        this.context = context;
    }

    public DialogLoginWelcome(Context context, int theme) {
        super(context, theme);
        this.context = context;
    }

    public DialogLoginWelcome(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.context = context;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        setContentView(R.layout.login_welcome_back);
        getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        mIUserLoginListener = this;
    }


    public void init(DialogLoginWelcome dialog){
        join = (TextView) dialog.findViewById(R.id.welcome_join_now_textView3);
        forgot = (TextView) dialog.findViewById(R.id.welcome_forgot_textView4);
        email = (EditText) dialog.findViewById(R.id.welcome_email_editText1);
        password = (EditText) dialog.findViewById(R.id.welcome_password_editText2);
        facebook = (LoginButton) dialog.findViewById(R.id.welcome_fb_connect_button1);
        login = (Button) dialog.findViewById(R.id.welcome_login_button2);

        facebook.setReadPermissions(Arrays.asList("email","public_profile"));
        facebook.setSessionStatusCallback(statusCallback);
        facebook.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {

            @Override
            public void onUserInfoFetched(GraphUser user) {
                session = Session.getActiveSession();
                Log.d("ohad", "facebook login changed! --- ");
                if(user != null){
                    ProgressBarClass.startLoading(context);
                    Log.d("ohad", user.toString());
                    cal = Calendar.getInstance();

                    mUserLoginHelper = new UserLoginHelper(mIUserLoginListener);
                    mUserLoginHelper.postUserDetails(user.getProperty("email").toString().trim(), user.getId().trim());
                }
            }

        });


        join.setOnClickListener(this);
        forgot.setOnClickListener(this);
        login.setOnClickListener(this);

        //email.setText("test@infibond.com");   
        //password.setText("a");    

        //email.setText("naamaraviv@walla.co.il");  //Production 
        //password.setText("naama1978raviv");       

        //email.setText("kraus@infibond.com");      //Dev
        //password.setText("kraus246"); 

        //email.setText("ohadshiffer28@walla.co.il");   //Production 
        //password.setText("1234"); 

        email.setText("noam@infibond.com"); //Production & Dev
        password.setText("nl555");

        //email.setText("max@wsiseo.co.il");    //Production 
        //password.setText("wsi768");
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){

        case R.id.welcome_join_now_textView3:                       //JOIN
            dismiss();
            DialogLoginSignup dialog = new DialogLoginSignup(context, R.style.DialogTheme);
            dialog.show();
            dialog.init(dialog);
            break;

        case R.id.welcome_forgot_textView4:                         //FORGOT
            //context.startActivity(new Intent(context, ForgotPassActivity.class));
            break;

        case R.id.welcome_fb_connect_button1:                       //FACEBOOK

            break;

        case R.id.welcome_login_button2:                            //LOGIN
            //VALIDATION OF INPUT SCREEN
            //IF FIELDS ARE EMPTY - SHOW ALERT MESSAGE.
            if (email.getText().toString().equals("")|| password.getText().toString().equals("")){ 
                Alert_Dialog.showAler(context, "Enter the required fields.", "Error!");
            } 

            else {        //IF FIELDS AREN'T EMPTY
                state = Utility.isOnline(context);
                if (state == true) { 
                    ProgressBarClass.startLoading(context);
                    new UserLoginHelper(this).postUserDetails(email
                            .getText().toString().trim(), password
                            .getText().toString().trim());

                } else if (state == false) {
                    Alert_Dialog.showAler(context, "Check Internet Connection", "Network Error!");
                }
            }
            break;

        }

    }


    @Override
    public void onUserLoginError(String errorMsg) {
        ProgressBarClass.dismissLoading();
        Alert_Dialog.showAler(context, errorMsg, "Error");
    }

    @Override
    public void onUserLoginSuccess(String response) {
        JSONObject res;
        try {  
            res = new JSONObject(response);

            Constant.me.setName(res.getString("full_name"));
            Constant.me.setEmail(res.getString("email"));
            Constant.me.setFirstName(res.getString("first_name"));
            Constant.me.setLastName(res.getString("last_name"));
            Constant.me.setBirth_date(res.getString("birthday"));
            Constant.me.setBody_value(res.getString("bio"));
            Constant.me.setProfileImageUrl(res.getString("picture"));
            Constant.me.setPrivacy(res.getString("privacy"));
            Constant.me.setPermissions(res.getString("permissions"));
            Constant.me.setUid(res.getString("uid"));
            Constant.me.setRelationship("self");

        } catch (JSONException e) {
            e.printStackTrace();
        } finally{
            new TimeHelper(this).getAlbumDetails(Constant.INFIBOND_DEV_SERVER_URL + 
                    "timeline/get?uid=" + Constant.me.getUid() + 
                    "&userType=user" + 
                    "&storiesLimitPerYear=6");
        }

    }

    @Override
    public void onTimelineError(String errorMsg) {
        ProgressBarClass.dismissLoading();
        Alert_Dialog.showAler(context, errorMsg, "Error");
    }

    @Override
    public void onTimelineSuccess(String response) {
        JSONObject res = null;
        try {  
            res = new JSONObject(response); 
        } catch (JSONException e) {
            e.printStackTrace();
        } 

        Intent intent = new Intent(context, MyInfiActivity.class);
        intent.putExtra("moments", res.toString());

        context.startActivity(intent);
        ProgressBarClass.dismissLoading();
        ((Activity) context).finish();
    }

    private Session.StatusCallback statusCallback = new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            if (state.isOpened()) {
                Log.d("ohad", "Facebook session opened. 3");
            } else if (state.isClosed()) {
                Log.d("ohad", "Facebook session closed. 3");
            }
        }
    };


}

然后你只需在驱动程序的Fluent Config文件中使用它,而在Car的一个文件中没有任何内容。

public class Driver 
{
    public int Id { get; set; }
    // Make this int? if a Driver can exist without a Car
    public int CarId { get; set; }
    public virtual Car { get; set; }
}